3 回答
TA贡献1946条经验 获得超3个赞
你也许可以这样做:
d = {
"Fruit_1" : ["mango", "apple"],
"Fruit_2" : ["apple"],
"Fruit_3" : ["mango", "banana", "apple", "kiwi", "orange"]
}
# list comprehension
mango_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)
TA贡献1828条经验 获得超13个赞
迭代d.items并检查mango值的存在。
In [21]: [key for key,value in d.items() if 'mango' in value]
Out[21]: ['Fruit_1', 'Fruit_3']
TA贡献1890条经验 获得超9个赞
幼稚的方法(遍历所有项目并寻找结果)有效但具有很高的复杂性,主要是在您必须执行大量请求时。你可以通过用lista替换你的值来稍微改进它set(为了更快的in查找),但这仍然会很慢(O(n**2)=>O(n)但还有改进的空间)。
如果您希望能够多次执行这些查询,最好重建字典,以便在构建后查找非常快,使用 collections.defaultdict
d = {
"Fruit_1" : ["mango", "apple"],
"Fruit_2" : ["apple"],
"Fruit_3" : ["mango", "banana", "apple", "kiwi", "orange"]
}
import collections
newd = collections.defaultdict(list)
for k,vl in d.items():
for v in vl:
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']
添加回答
举报