Ravi
Ravi

Reputation: 157

creating nested dictionary from list of dictionary

i have dictionary dictionary like bellow (parsed lspci info)

original dictionary:

d={'host':{'v':'v1','d':'d1','sv':'sv1','sd':'sd1'},
    'ether':{'v':'v2','d':'d2','sv':'sv2','sd':'sd2'}}

dictionary to check with original dictionary:

to_check={'host':['v','d'],'ether':['v','d','sv']}

i need output like this

output_dict={'host':{'v':'v1','d':'d1'},'ether':{'v':'v2','d':'d2','sv':'sv2'}}

How do i achieve using dict comprehension ?? is there another easy way

Upvotes: 2

Views: 101

Answers (3)

Nafiul Islam
Nafiul Islam

Reputation: 82440

>>> {key: {l: d.get(key).get(l) for l in lst} for key, lst in to_check.items()}
{'host': {'d': 'd1', 'v': 'v1'}, 'ether': {'sv': 'sv2', 'd': 'd2', 'v': 'v2'}}

It is safer to use get as opposed to [] because it gives you more flexibility, for example if the key x is not present (I just added this to to_check), then you can set another value in get to give you a default value:

>>> {key: {l: d.get(key, 'Does Not Exist').get(l, 'Does Not exit') for l in lst} for key, lst in to_check.items()}
{'host': {'x': 'Does Not exit', 'd': 'd1', 'v': 'v1'}, 'ether': {'sv': 'sv2', 'd': 'd2', 'v': 'v2'}}

Upvotes: 1

wim
wim

Reputation: 362488

>>> {k:{v:d[k][v] for v in vs} for k,vs in to_check.items()}
{'ether': {'d': 'd2', 'sv': 'sv2', 'v': 'v2'}, 'host': {'d': 'd1', 'v': 'v1'}}

Upvotes: 1

thefourtheye
thefourtheye

Reputation: 239443

print {k:{key:d[k][key] for key in to_check[k] if key in d[k]} for k in to_check}

Output

{'ether': {'d': 'd2', 'v': 'v2', 'sv': 'sv2'}, 'host': {'d': 'd1', 'v': 'v1'}}

Upvotes: 5

Related Questions