Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract sub dictionary from keys that appear in a given list [duplicate]

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}

like image 469
kjanko Avatar asked Jan 03 '23 20:01

kjanko


1 Answers

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'}
like image 64
hiro protagonist Avatar answered Jan 16 '23 20:01

hiro protagonist