python - 通过 Python 字典中的值查找键

标签 python dictionary

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(nameagelist)

    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)

我想返回 19 岁的人的名字。如何按值搜索字典并返回键?

最佳答案

print [key for (key,value) in nameagedict.items() if value == 19]

nameagedict.items() 为您提供字典中所有项目的列表,作为(键,值)元组。

关于python - 通过 Python 字典中的值查找键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4882291/

相关文章:

python - Swagger-ui 连接未找到 Python 嵌套函数

python - 在 Python 中的列表上循环函数

python - 将多行文本文件拆分为多行 csv 文件

Java 8 Map of Collections 从集合中删除元素,如果为空则删除条目

Python添加/更新任何深度的dict元素

python - Pygame Rect,参数是什么?

python - Django 教程 NoReverseMatch

python - 我如何仅选择/格式化字典中的值到列表或 numpy 数组中?

python - 如何根据列表中的元素从 Python 字典中删除元素?

python - 从具有可变长度的列表字典创建数据框