首页 > 解决方案 > 在字典之间执行查找

问题描述

我在名为 stats 的变量中有多个字典

print (stats)
{'CAT1': [{'Fruit': 'Apple', 'Sound': 'Meow', 'Sleep': 'Normal', 'Color': 'blue', 'Eye': 'blue', 'Tail': 'Short'}]}
{'CAT2': [{'Fruit': 'Orange', 'Sound': 'Meow', 'Sleep': 'Less', 'Color': 'orange', 'Eye': 'black', 'Tail': 'long'}]}
{'CAT3': [{'Fruit': 'Mango', 'Sound': 'Meow', 'Sleep': 'Abnormal', 'Color': 'blue', 'Eye': 'black', 'Tail': 'Short'}]}
{'CAT4': [{'Fruit': 'Peach', 'Sound': 'Meow', 'Sleep': 'Normal', 'Color': 'yellow', 'Eye': 'black', 'Tail': 'short'}]}

我还有另一本字典-所有者

print(Owner)
{'CAT1': ['this cat belongs to YZMIKE'], 'CAT2': ['this cat belongs to AAJOHN'], 'CAT3': ['this cat belongs to FPROB'], 'CAT4': ['this cat belongs to LDKATE']}

我想根据两个字典中的 KEY 进行查找以获得以下输出

{
'this cat belongs to YZMIKE':[{'Fruit': 'Apple', 'Sound': 'Meow', 'Sleep': 'Normal', 'Color': 'blue', 'Eye': 'blue', 'Tail': 'Short'}]
'this cat belongs to AAJOHN':[{'Fruit': 'Orange', 'Sound': 'Meow', 'Sleep': 'Less', 'Color': 'orange', 'Eye': 'black', 'Tail': 'long'}]
'this cat belongs to FPROB':[{'Fruit': 'Mango', 'Sound': 'Meow', 'Sleep': 'Abnormal', 'Color': 'blue', 'Eye': 'black', 'Tail': 'Short'}]
'this cat belongs to LDKATE':[{'Fruit': 'Peach', 'Sound': 'Meow', 'Sleep': 'Normal', 'Color': 'yellow', 'Eye': 'black', 'Tail': 'short'}]
}

感谢您的帮助...我是 python 新手,不知道如何执行此查找..

标签: pythonlistdictionary

解决方案


我认为您的问题中的数据格式存在问题。看起来您有两个具有相同键的字典,因此,如果您想创建一个字典,将 dict 1 中的键替换为 dict 2 中列表中的值:

new_dict = dict((Owner[x][0],stats[x]) for x in stats)

或者为了更加安全:

new_dict = dict((Owner[x][0],stats[x]) for x in stats if x in Owner)

推荐阅读