22

In python... I have a list of elements 'my_list', and a dictionary 'my_dict' where some keys match in 'my_list'.

I would like to search the dictionary and retrieve key/value pairs for the keys matching the 'my_list' elements.

I tried this...

    if any(x in my_dict for x in my_list):
          print set(my_list)&set(my_dict)

But it doesn't do the job.

Nick Butler
  • 24,045
  • 4
  • 49
  • 70
peixe
  • 1,272
  • 3
  • 14
  • 31
  • 6
    Please don't name your variables `list` or `dict`. It confuses the heck out of people (and possibly then Python interpreter, too, if you're not careful). – Tim Pietzcker Jun 28 '11 at 10:29

6 Answers6

43

(I renamed list to my_list and dict to my_dict to avoid the conflict with the type names.)

For better performance, you should iterate over the list and check for membership in the dictionary:

for k in my_list:
    if k in my_dict:
        print(k, my_dict[k])

If you want to create a new dictionary from these key-value pairs, use

new_dict = {k: my_dict[k] for k in my_list if k in my_dict}
mirekphd
  • 4,799
  • 3
  • 38
  • 59
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • adding `my_dict.keys()` would make it much faster, as it would only search the `keys` in the `dict`. Or to search in values just use `my_dict.values()` – Deepak Harish Sep 16 '22 at 04:52
16

Don't use dict and list as variable names. They shadow the built-in functions. Assuming list l and dictionary d:

kv = [(k, d[k]) for k in l if k in d]
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
13
 new_dict = dict((k, v) for k, v in dict.iteritems() if k in list)

Turning list into a set set(list) may yield a noticeable speed increase

Rob Cowie
  • 22,259
  • 6
  • 62
  • 56
4

Try This:

mydict = {'one': 1, 'two': 2, 'three': 3}
mykeys = ['three', 'one','ten']
newList={k:mydict[k] for k in mykeys if k in mydict}
print newList
{'three': 3, 'one': 1}
Vikram Singh Chandel
  • 1,290
  • 2
  • 17
  • 36
3

What about print([kv for kv in dict.items() if kv[0] in list])

Alexander Gessler
  • 45,603
  • 7
  • 82
  • 122
1

Here is a one line solution for that

{i:my_dict[i] for i in set(my_dict.keys()).intersection(set(my_list))}
Palash Jhamb
  • 605
  • 6
  • 15