Adding keys and values to a Python dictionary

To add a single key and value to an existing dictionary, just use the [] operator:

fruits = {'apple': 1, 'pear': 2, 'orange': 3}
fruits['cherry'] = 4

To add multiple keys and values, you can use the update method. If any of the new keys already exist in the dictionary, the new values replace the old ones.

You can use update() to add the contents of another dictionary:

fruits.update({'apricot': 5, 'mango': 6})

Or, you can pass it keyword arguments. In this case the dictionary keys you are adding must be valid Python identifiers:

fruits.update(banana=7, damson=8)

Or, you can pass it an iterator over tuples:

fruits.update(zip(['gooseberry', 'peach'], [9, 10]))

Or, you can pass it a generator expression:

fruits.update((key, value) for key, value in [('pineapple', 11), ('grape', '12')])

Finally, you can pass it a dict comprehension

fruits.update({(key, value) for key, value in [('strawberry', 13), ('plum', '14')]})

4.10. Mapping Types — dict
PEP 289 — Generator Expressions
PEP 274 — Dict Comprehensions