简体   繁体   中英

Python How do I search through a dictionary if the the value is a list and I have the first number in the list?

So if I have a dictionary like

    mydict = {"a":[0,0], "b":[2,1], "c":[2,2], "d":[0,0], "e":[3,1]}

How would I search for all keys that the first number in its value is 2 (so I get "b" and "c")?

You can try this:

mydict = {"a":[0,0], "b":[2,1], "c":[2,2], "d":[0,0], "e":[3,1]}
final_vals = [a for a, [b, c] in mydict.items() if b == 2]

Output:

['c', 'b']

First iterate your dict and then verify your 1st element of list using if, here is the one - liner sol using list comprehension

mydict = {"a":[0,0], "b":[2,1], "c":[2,2], "d":[0,0], "e":[3,1]}
print([ k for k, v in mydict.items() if v[0]==2])
['c', 'b']

You can use list comprehension to gather the keys as below:

mydict = {"a":[0,0], "b":[2,1], "c":[2,2], "d":[0,0], "e":[3,1]}
keys = [key for key, value in mydict.items() if value[0] == 2]
print(keys)

Output:

['c', 'b']

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