python - 在字典之间执行查找
问题描述
我在名为 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 新手,不知道如何执行此查找..
解决方案
我认为您的问题中的数据格式存在问题。看起来您有两个具有相同键的字典,因此,如果您想创建一个字典,将 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)
推荐阅读
- apache-poi - Apache POI:获取公式错误的更多详细信息
- css - CSS:Chrome 检查器使用变换和自定义 css 变量动画失败
- swift - SwiftUI 中的可选状态或绑定
- ssis - 我们可以在 kimball 方法中的分析方面制作数据集市吗?
- excel - 在excel应用程序中。如何在单个图表中表示多个项目的趋势?
- ios - 如何在 Swift 中将我的长正则表达式提取到多行字符串?
- swift - 如果附件纹理是 type2DMultisample,则将 MTKView 渲染目标保存到 CGImage
- algorithm - 确定每个人阅读一本书的最短总时间
- java - Android:初始化Intent时找不到Class的符号
- .htaccess - htaccess 去掉地址栏中的#