简体   繁体   中英

Look up array of values as the value of a key of a dictionary in Python

I have a dictionary like this:

dic = {'Mr A':[1200,1500,1100], 'Mr B':[2200, 3000, 1200]}

and I want to look up a value from the array of values to get keys which satisfy the query.

I tried this,

>>> 1200 in dic.values()
False

I get a match only when I look up the entire array.

>>> [1200,1500,1100] in dic.values()
True

How do I look inside the arrays and get the keys which match the query?

Any thoughts?

Using list comprehension:

>>> dic = {'Mr A':[1200,1500,1100], 'Mr B':[2200, 3000, 1200]}
>>> [key for key, value in dic.iteritems() if 1200 in value]
['Mr A', 'Mr B']
>>> [key for key, value in dic.iteritems() if 3000 in value]
['Mr B']

dic.values() returns [[1200, 1500, 1100], [2200, 3000, 1200]] which is a list of lists.

a in b evaluates to True only when one or more of the elements of b is equal to a .

So of course 1200 is not in dic.values() because:

1200 != [1200, 1500, 1100]

and

1200 != [2200, 3000, 1200] .

If you want to see if 1200 is in any of the sublists, you can:

import itertools 
1200 in itertools.chain(*dic.values())

See: http://docs.python.org/2/library/itertools.html#itertools.chain for details for itertools.chain

If you actually want to know which key the list in which your element appears belongs to you can:

[k for k, v in dic.items() if elem in v]

where you would first set elem to the value you are searching for (such as 1200 ).

This should return a list of all the keys that are associated with a list that contains your value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM