我做了一个函数,它将在字典中查找年龄并显示匹配的名字:

dictionary = {'george' : 16, 'amber' : 19}
search_age = raw_input("Provide age")
for age in dictionary.values():
    if age == search_age:
        name = dictionary[age]
        print name

我知道如何比较和查找年龄,只是不知道如何显示这个人的名字。此外,由于第5行,我得到了一个KeyError。我知道这是不正确的,但我不知道如何让它向后搜索。


当前回答

在我的情况下,最简单的方法是实例化字典在你的代码,然后你可以从它调用键如下

这是我们班有字典

class Config:

def local(self):
    return {
        "temp_dir": "/tmp/dirtest/",
        "devops": "Mansur",
    }

实例化你的字典

config =  vars.Config()
local_config = config.local()

最后调用你的字典键

patched = local_config.get("devops")

其他回答

我们可以通过以下方法得到dict的Key:

def getKey(dct,value):
     return [key for key in dct if (dct[key] == value)]

使用列表理解的一行解决方案,如果值可能出现多次,则返回多个键。

[key for key,value in mydict.items() if value == 16]

没有。Dict不是这样使用的。

dictionary = {'george': 16, 'amber': 19}
search_age = input("Provide age")
for name, age in dictionary.items():  # for name, age in dictionary.iteritems():  (for Python 2.x)
    if age == search_age:
        print(name)

这是一个真正的“可逆字典”,基于Adam Acosta的解决方案,但强制val-to-key调用是唯一的,容易从值返回键:

from collections import UserDict


class ReversibleDict(UserDict):
    def __init__(self, enforce_unique=True, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.val_to_keys = {}
        self.check_val = self.check_unique if enforce_unique else lambda x: x

    def __setitem__(self, key, value):
        self.check_val(value)
        super().__setitem__(key, value)
        self.val_to_keys[value] = key

    def __call__(self, value):
        return self.val_to_keys[value]

    def check_unique(self, value):
        assert value not in self.val_to_keys, f"Non unique value '{value}'"
        return value

如果你想强制字典值的唯一性,确保set enforce_unique=True。从值中获取键只需做rev_dict(value),从键中调用值只需像往常一样做dict['key'],这里是一个用法示例:

rev_dict = ReversibleDict(enforce_unique=True)
rev_dict["a"] = 1
rev_dict["b"] = 2
rev_dict["c"] = 3
print("full dictinoary is: ", rev_dict)
print("value for key 'b' is: ", rev_dict["b"])
print("key for value '2' is: ", rev_dict(2))
print("tring to set another key with the same value results in error: ")
rev_dict["d"] = 1

考虑使用Pandas。正如William McKinney的《Python for Data Analysis》中所述

另一种考虑级数的方法是固定长度的有序级数 Dict,因为它是索引值到数据值的映射。它可以是 在很多情况下,你可能会用到字典。

import pandas as pd
list = {'george':16,'amber':19}
lookup_list = pd.Series(list)

要查询您的系列,请执行以下操作:

lookup_list[lookup_list.values == 19]

收益率:

Out[1]: 
amber    19
dtype: int64

如果您需要对输出进行任何其他转换 回答成一个列表可能有用:

answer = lookup_list[lookup_list.values == 19].index
answer = pd.Index.tolist(answer)