Alice - 8 months ago 20

Python Question

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())`

new_dict={}

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 :

`{key:value}`

{key2:value2}

ecc..

How can obtain an unique dictionary??

Answer

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()}
```