Generating a Dictionary Value Summary

Generate a Simple Dictionary Value Summary

Today’s post will be a short post – on something I recently needed to do for a project at work. My program assigned orders to a particular disposition. The domain of the problem isn’t really relevant – but I used a dictionary with the unique order number as the key and one of several values could be the value.

I wanted to post a message, once the process had completed, to inform me of the outcome summary. How many orders got disposition A, B, C and so on.

I dug around on the internet to find a solution – as I couldn’t easily think of one – but was not immediately satisfied with any I found. So I went back to work on the problem on my own.

Below, we are creating a dictionary with keys A-I (in my work solution these were order numbers) and they are each assigned one of three colors: RED, BLUE or GREEN (in my work solution these were order dispositions).

If I wanted to display a summary, indicating how may dictionary elements had values in each color there are probably many ways to do it – but given the post I just wrote on comprehensions I wanted to try to solve it that way.

Here is my solution (and it is essentially one line of code):

d = {'A':'RED', 'B':'BLUE', 'C':'RED', 'D':'GREEN', 
     'E':'RED', 'F':'BLUE', 'G':'GREEN', 'H':'BLUE', 'I':'BLUE'}

{e:list(d.values()).count(e) for e in sorted(set(d.values()))}
{'BLUE': 4, 'GREEN': 2, 'RED': 3}

This comprehension starts by casting the source dictionary values as a set, thus getting a unique list containing only RED, BLUE and GREEN.

{'BLUE', 'GREEN', 'RED'}

Then the values are sorted (not required), using the sorted function and iterated over with each color becoming e during it’s iteration. We set the target dictionary key to e’s current value and then we go back to the source dictionary, casting the dict_values object (accessible as d.values()) to a list. From there we can use the list object’s count method to get a count of the values with the color currently stored in e and assigning it the associated dictionary key’s value in the comprehension.

There may be a more elegant way to do this – but since I hadn’t seen one in my quick search – I thought I would take the time to document how I achieved it.