Consider that I have a dictionary that looks like this:
{1=>a, 2=>b, 3=>c, 4=>d}
and a list that looks like this:
[1, 2, 3]
is there a method that'd return me a subdictionary only containing
{1=>a, 2=>b, 3=>c}
a regular dict-comprehension would do that:
d = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
keys = [1, 2, 3]
dct = {key: d[key] for key in keys}
print(dct) # {1: 'a', 2: 'b', 3: 'c'}
there are 2 ways to handle keys in keys
that are not in the original dictionary:
keys = [1, 2, 3, 7]
# default value None
dct = {key: d[key] if key in d else None for key in keys}
print(dct) # {1: 'a', 2: 'b', 3: 'c', 7: None}
# ignore the key if it is not in the original dict
dct = {key: d[key] for key in set(keys).intersection(d.keys())}
print(dct) # {1: 'a', 2: 'b', 3: 'c'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With