Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary keys match on list; get key/value pair

Tags:

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.

like image 878
peixe Avatar asked Jun 28 '11 10:06

peixe


People also ask

How do I get a list of keys and values in a dictionary?

The methods dict. keys() and dict. values() return lists of the keys or values explicitly. There's also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary.

How do you check if a key-value pair is in a dictionary?

Check if a key-value pair exists in a dictionary: in operator, items() To check if a key-value pair exists in a dictionary, i.e., if a dictionary has/contains a pair, use the in operator and the items() method. Specify a tuple (key, value) . Use not in to check if a pair does not exist in a dictionary.

Can a key-value pair be a list?

A value in the key-value pair can be a number, a string, a list, a tuple, or even another dictionary.


2 Answers

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]
like image 34
Felix Kling Avatar answered Oct 02 '22 09:10

Felix Kling


(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}
like image 72
Sven Marnach Avatar answered Oct 02 '22 09:10

Sven Marnach