combining two dictionary to create a new dictionary in python


I have a dictionary that maps orders to bins.

orders_to_bins={1: 'a', 2:'a', 3:'b'}

I have another dictionary that shows the items in the orders.


I need to create a new dictionary that shows the items in the bins like this.


I am looking for hints or solutions on how to achieve the last dictionary from the first two.

Asked By: mars



This answer uses a defaultdict, which is essentially a regular python dictionary where every new value is automatically initialized to be a particular type (in this case list).

For every (key, value)-pair in the orders_to_bins (extracted with the .items() method), we extend the items_in_bins list for a particular key, which is the bin_name from whatever is in items.

Here is what that looks like:

from collections import defaultdict

items_in_bins = defaultdict(list)

for order, bin_name in orders_to_bins.items():
>>> print(dict(items_in_bins))
{'a': [49, 50, 51, 62, 60, 63, 64, 65], 'b': [70, 71, 72, 74]}

Note, in the print statement, I am making it back to a regular dict for ease of reading, but that is not necessary.

Also note, if you are unsure if items will be populated, you could do items.get(order, []) instead of items[order] to ensure that it does not fail on missing keys. But, that is up to you and dependent on what you are trying to do (i.e. maybe that is a valid error).

Answered By: chaimp
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.