Tag Archives: Dictionary

Sort a list of dictionaries by a key In all of them

If you have a list of dictionaries like this:

fruit = [{'Name': 'Banana', 'Colour': 'Yellow', 'Shape': 'Bent'},
            {'Name': 'Apple', 'Colour': 'Red', 'Shape': 'Round'}]

And you want to sort them by the Name key, you can do one of two things.

Method 1: Use a lambda

print sorted(fruit, key=lambda k: k['Name'])

Method 2: Use itemgetter

from operator import itemgetter
print sorted(fruit, key=itemgetter('Name')) 

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')]})

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