I very often run into the need of comparing Python dictionaries. For example, we have two dictionaries of daily sale/revenue for last week and this week where each day of week is a key and the revenue is the value. Some days we may or may not have any sell at all. We may need to compare to see if which week we have more days of sales, or we may need to compare what day of week we have the most sales. To solve this kind of business question, it often comes down to the need of comparing dictionaries.
So, today we will explore some of the tips that I often find very useful when we need to compare dictionaries.
First, let's create two dictionaries, 'products' and 'sales' as our sample data as below:
We need to find out the common keys in the key sets of the two dictionaries, so that we can later link them to find out the according sales of each product.
Sometimes, we need to find the keys which are in one dictionary but not in the other dictionary.
In many cases, we need to find out the duplicate items, both key and value, in two dictionaries.
And, the one that I like the most is dictionary comprehension. We often use a lot of List comprehension in Python. However, when it comes to Dictionary, some time Dictionary comprehension does the job very well and make the code look very clean.
Happy coding!
Source code: https://github.com/MaiaNgo/python-best-practices/blob/master/dictionaries_comparision.ipynb
Comments