-1

Edit: I've updated my question to clarify my goal.

Is there a way to speed-up this code by using reduce() or some other fast method 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}

3 Answers 3

5

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)))
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to know how about to use functools.reduce.

import functools
old_dict = {'a': 1, 'b': 2, 'c': 3}
keys = ['a', 'c', 'd']
res = functools.reduce(lambda d,v: {**d, **{v : old_dict.get(v, None)}}, keys, {})
print(res)

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

Comments

0

You're better off using @Peter 's answer. But here's an option using functools.reduce.

from functools import reduce

old_dict = {'a': 1, 'b': 2, 'c': 3}
keys = ['a', 'c', 'd']

def func(dct, key, old_dict=old_dict):
    dct[key] = old_dict.get(key)
    return dct

new_dict = reduce(func, keys, {})
print(new_dict)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.