user1893110 - 8 months ago 34

Python Question

Suppose I have a dict like so:

`d = {27: 32, 28: 41, 29: 29, 30: 29, 31: 67, 32: 65}`

And a list:

`l = [27, 30, 31]`

for n in l:

d2 = {k:v for k,v in d.items() if k in n}

Why is this not permissible? What can I do instead?

Answer

It would be enough to get a filtered dict in this way:

```
d = {27: 32, 28: 41, 29: 29, 30: 29, 31: 67, 32: 65}
l = set([27, 30, 31])
d2 = {k:v for k,v in d.items() if k in l}
print(d2)
```

The output:

```
{27: 32, 30: 29, 31: 67}
```

The expression `... if k in n`

within your list comprehension while iterating through `for n in l:`

means that you are searching a numerical key within a digit(number) - it's like we are searching `27 in 27`

which it's pointless in this case.

Also, as @Goodies fairly reminded, a `set`

object would be more preferable in case of large sequences.

Membership testing with sets and dictionaries is much faster, O(1), than searching sequences, O(n)

Source (Stackoverflow)