Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

Pandas Dictionary: How to return a key by matching an input value to multiple values assinged to a single key

I have a dicticionary where each key has multiple values.I'm trying to obtain the key from a dictionary by matching an input value to the values for a certain key

areas={     '1':['a', 'b'],
            '2':['c', 'd', 'e'],
            '3':['f' 'g', 'h', 'i','j', 'k' ],
            '4': ['l', 'm','n'],
            '5': ['o' , 'o', 'q', 'r' 's' 't']
           }

So far, i've tried this, but in both cases I get an empty value (result is []), instead of '2'.

input_area='c'
x=[key for key in areas_dict if input_area in areas_dict.values()]
x

input_area='c'
x=[k for k, v in areas_dict.items() if input_area==v]
x
question from:https://stackoverflow.com/questions/65892520/pandas-dictionary-how-to-return-a-key-by-matching-an-input-value-to-multiple-va

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You've almost done it. Since you need to look inside each key's values, you must access areas[key] for each key inside the list comprehension. Using areas_dict.values() doesn't work because it returns all the values from that dictionary at once.

It must be something like:

input_area = 'c'
x = [key for key in areas if input_area in areas[key]]

print(x)

The output is as follows:

['2']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...