Hi, I'm Harlin and welcome to my blog. I write about Python, Alfresco and other cheesy comestibles.

Python: How to Merge and Sort Dictionaries by Values

If you ever get two dictionaries that you would like to merge together, you can do so with the "**" operator. How does that work? The "**" operator takes a dictionary and extracts its contents and passes them as parameters to a function.

Consider that our person has some keys and values in two different dictionaries but you would like to merge them together to make a one "person" dict:

person_a = {
    'Name': 'John Doe',
    'Age': 30,
    'Hair color': 'brown',
}

person_b = {
    'Nationality': 'American',
    'Education level': 'BS - Computer Science',
}

We can put them together by building a new dictionary and adding the contents together and make one dict:

person = {**person_a, **person_b}

for k, v in person.items():
    print('{}: {}'.format(k, v))

If you're using Python 2.7, you can build a dictionary object using the original person_a and then adding the contents of person_b like so:

# for Python 2.7:

person = dict(person_a, **person_b)

for k, v in person.items():
    print('{}: {}'.format(k, v))

If you have a dictionary of users and grades and want to sort them:

scores = {
    'Mike': 75,
    'Phil': 90,
    'Bill': 85,
    'Larry': 71,
    'Glenn': 99,
    'Maria': 80,
    'Rosa': 77,
}

Out of the box, Python makes no guarantee of how a dictionary object will be sorted. So, if you don't use something like sorted(), when you iterate over a dictionary, there likely won't be an order to the keys and values when they are printed out.

You can use sorted() with parameters of the scores items and set the key for sorting to the 2nd element using the operator.itemgetter(1) function:

import operator

score_list = sorted(scores.items(), key=operator.itemgetter(1))

for k, v in score_list:
    print(k, v)

score_list.reverse()

for k, v in score_list:
    print(k, v)

Any Comments, Always Welcome!