如何从列表字典的值中获取所有键?

我有一本这样格式的字典


d = {

    "Fruit_1" : ["mango", "apple"],

    "Fruit_2" : ["apple"],

    "Fruit_3" : ["mango", "banana", "apple", "kiwi", "orange"]

}

我将一个值作为“芒果”传递,并且我想获取所有只出现芒果的对应键。我无法在值发生的地方获得相应的键。


LEATH
浏览 343回答 3
3回答

智慧大石

你也许可以这样做:d = {    "Fruit_1" : ["mango", "apple"],    "Fruit_2" : ["apple"],    "Fruit_3" : ["mango", "banana", "apple", "kiwi", "orange"]}# list comprehensionmango_keys = [fruit for fruit in d.keys() if "mango" in d[fruit]]print(mango_keys)       # ['Fruit_1', 'Fruit_3']         # or more traditional for-loop (but non pythonic)for fruit in d.keys():    if "mango" in d[fruit]:        print(fruit)

慕田峪7331174

迭代d.items并检查mango值的存在。In [21]: [key for key,value in d.items() if 'mango' in value]Out[21]: ['Fruit_1', 'Fruit_3']

当年话下

幼稚的方法(遍历所有项目并寻找结果)有效但具有很高的复杂性,主要是在您必须执行大量请求时。你可以通过用lista替换你的值来稍微改进它set(为了更快的in查找),但这仍然会很慢(O(n**2)=>O(n)但还有改进的空间)。如果您希望能够多次执行这些查询,最好重建字典,以便在构建后查找非常快,使用 collections.defaultdictd = {&nbsp; &nbsp; "Fruit_1" : ["mango", "apple"],&nbsp; &nbsp; "Fruit_2" : ["apple"],&nbsp; &nbsp; "Fruit_3" : ["mango", "banana", "apple", "kiwi", "orange"]}import collectionsnewd = collections.defaultdict(list)for k,vl in d.items():&nbsp; &nbsp; for v in vl:&nbsp; &nbsp; &nbsp; &nbsp; newd[v].append(k)print(newd)print(newd["mango"])这是重建的字典:defaultdict(<class 'list'>, {'apple': ['Fruit_2', 'Fruit_3', 'Fruit_1'], 'orange': ['Fruit_3'], 'banana': ['Fruit_3'], 'kiwi': ['Fruit_3'], 'mango': ['Fruit_3', 'Fruit_1']})这是对“芒果”的查询:['Fruit_3', 'Fruit_1']
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python