如何根据Python中的值显示字典键

时间:2017-11-29 16:45:34

标签: python python-3.x dictionary

我有一本字典和一份清单:

dct = {'A': a1, 'B': b2}

a1 = [0, 2, 4, 6, 8]
b2 = [1, 3, 5, 7, 9]

在此基础上制定清单:

c = [2, 8, 5]

你怎么回到字典键?要使c列表显示为:

c2 = [AAB]

3 个答案:

答案 0 :(得分:2)

您可以构建从列表中的值到字典键的附加映射,然后使用它来查找列表<form autoComplete="new-password" ... > <input name="myInput" type="text" autoComplete="off" id="myInput" placeholder="Search field" /> </form> 中值的键:

c

答案 1 :(得分:1)

迭代方法:

a1 = [0, 2, 4, 6, 8]
b2 = [1, 3, 5, 7, 9]
dct = {'A': a1, 'B': b2}
c = [2, 8, 5]
result = ''

for i in c:
    for k, v in dct.items():
        if i in v:
            result += k
            break

print(result)   # AAB

答案 2 :(得分:0)

对象/字典 有一个名为.viewkeys()的方法

试 dct = {&#39; A&#39;:&#39; a1&#39;,&#39; B&#39;:&#39; b2&#39;} 打印(dct.viewkeys())