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

Populate dict using reduce() instead of loop

Is there a way to sped-up this code by using reduce() rather than the for loop?
I looked at many similar questions but I did not find an answer.

old_dict = {'a': 1, 'b': 2, 'c': 3}
keys = ['a', 'c', 'd']
new_dict = {}
for key in keys:
    new_dict[key] = old_dict.get(key)
print(new_dict)

# prints:
# {'a': 1, 'c': 3, 'd': None}

>Solution :

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

If you’re not set on using reduce, you can chain a few built in functions together which should be very efficient.

new_dict = dict(zip(keys, map(old_dict.get, keys)))
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