Alice Alice - 1 year ago 65
Python Question

Updating correctly keys in dictionary in Python?

I have a dictionary (d2) and I have to create a new dictionary (new_dict) containing only keys that satisfy a condition.

This is my code:

d2 = dict((y,x) for x,y in d.iteritems())

for name in list:
for keyx in d2:
if name in keyx:
new_dict=dict((keyx,d2[keyx]) for v in d2.itervalues())
print new_dict

But when I print new_dict I obtain a new_dict for each key :


How can obtain an unique dictionary??

Answer Source

Here's how to do it with an example.

>>> f={'c':1,'d':2,'e':3}
>>> l=['c','d']
>>> {i:f[i] for i in f if any([k in i for k in l])}
{'c': 1, 'd': 2}

For your use case it will simply be.

new_dict = {i:d2[i] for i in d2 if any([k in i for k in list])}  

That said, please refrain from using variable names like list.

Also, instead of

d2 = dict((y,x) for x,y in d.iteritems())

you could just do

d2 = {y:x for x,y in d.iteritems()}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download