Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

items={1:[49,50,51,62],
       2:[60,63,64,65],
       3:[70,71,72,74]}

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

items_in_bins={'a':[49,50,51,62,60,63,64,65],
               'b':[70,71,72,74]}

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

>Solution :

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():
    items_in_bins[bin_name].extend(items[order])
>>> 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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading