Find keys through values in a dict for Python
NAMES = ['Alice', 'Bob','Cathy','Dan','Ed','Frank',
'Gary','Helen','Irene','Jack', 'Kelly','Larry']
AGES = [20,21,18,18,19,20,20,19,19,19,22,19]
def nameage(a,b):
nameagelist = [x for x in zip(a,b)]
nameagedict = dict(na开发者_如何转开发meagelist)
return nameagedict
def name(a):
for x in nameage(NAMES,AGES):
if a in nameage(NAMES,AGES).values():
print nameage(NAMES,AGES).keys()
print name(19)
I am trying to return the names of the people aged 19. How do I search the dictionary by value and return the key?
print [key for (key,value) in nameagedict.items() if value == 19]
nameagedict.items()
gives you a list of all items in the dictionary, as (key,value) tuples.
I had a similar problem. Here's my solution which returns the keys and values as an array of tuples.
filter(lambda (k,v): v==19, nameagedict.items())
Partial solution
names = {age:sorted([name for index,name in enumerate(NAMES) if age == AGES[index]]) for age in sorted(set(AGES))}
print(names)
Returns:
{18: ['Cathy', 'Dan'], 19: ['Ed', 'Helen', 'Irene', 'Jack', 'Larry'], 20: ['Alice', 'Frank', 'Gary'], 21: ['Bob'], 22: ['Kelly']}
Leave out sorted() if you wish. You could also add count() so the data returned something like
{18: [('Cathy',3), ('Dan',7), ...}
if there were 3 Cathys and 7 Dans.
Although the above looks short I suspect an actual for loop would iterate over the original lists less.
Or even better:
def names(age):
index = 0
while index < len(AGES):
if AGES[index] == age:
yield NAMES[index]
index += 1
print('19 year olds')
for name in names(19):
print(name)
精彩评论