python-3.x - python字典 - 合并两个字典并在它们匹配时附加键值
问题描述
我有两个字典列表。一种是嵌套分层格式,另一种是简单的字典列表。我正在尝试像我们在 pandas 或 sql 中那样做的“外部连接”,比如“加入”。基本上,我试图从字典中捕获键/值,而另一个键/值不存在。这是我尝试过的。
字典 1:大型嵌套字典:
data = [
{'file_name': 'abc.pdf',
'year':'2016',
'overview': {
'student_id': '123abc',
'name': 'Adam Smith',
'courses': ['Math', 'Physics'],
}},
{'file_name': 'def.pdf',
'year':'2017',
'overview': {
'student_id': '123abc',
'name': 'Adam Smith',
'courses': ['Arts'],
}}
]
字典2:
mapper =[{
'year':'2016',
'student_id': '123abc',
'counselor':'Matthews',
'grades':'85'
}]
尝试/合并
pairs = zip(mapper,data)
试试 1
[(x,y) for x, y in pairs if x['student_id'] == y['overview']['student_id']]
>> gives result:
[({'year': '2016',
'student_id': '123abc',
'counselor': 'Matthews',
'grades': '85'},
{'file_name': 'abc.pdf',
'year': '2016',
'overview': {'student_id': '123abc',
'name': 'Adam Smith',
'courses': ['Math', 'Physics']}})]
尝试2:
[(x,y) for x, y in pairs if x['student_id'] == y['overview']['student_id'] & x['year'] == y['year']]
# gives errors: `TypeError: unsupported operand type(s) for &: 'str' and 'str'`
试图得到这个结果:如果两个字典中的 year 和 student_id 匹配,那么给出这个结果。从字典 2:我试图匹配如果 year 和 student_id 匹配然后填充辅导员,'grades' 到字典 1。如果不匹配,则给定字典元素。
new_data = [
{'file_name': 'abc.pdf',
'year':'2016',
'overview': {
'student_id': '123abc',
'name': 'Adam Smith',
'courses': ['Math', 'Physics'],
'counselor':'Matthews',
'grades':'85'
}},
{'file_name': 'def.pdf',
'year':'2017',
'overview': {
'student_id': '123abc',
'name': 'Adam Smith',
'courses': ['Arts'],
}}
]
解决方案
在这种情况下,我认为zip
这不是一个好的选择。我会将数据的 ['overview'] 字典与映射器字典合并:
for idx, i in enumerate(data):
for j in mapper:
if i['overview']['student_id'] in j['student_id'] and i['year'] == j['year']:
data[idx]['overview'] = {**i['overview'], **j}
推荐阅读
- json - 在 Postman 中测试用于从 Skyscanner 的 api 获取实时价格的功能“创建会话”时出错 - 结果为空或 429 错误代码
- apache-nifi - 访问 NiFi UI 的问题
- solr - 是否可以从 Solr 5.x 升级到 Solr 8.x?
- java - 在 ColdFusion 版本 2018 Update 11 上将 tomcat 版本 9.0.41 升级到 9.0.46
- javascript - 自添加新脚本标签后,引导模式不再显示
- android - 在 Kotlin 的 Firestore 中找不到数据时如何处理 NullPointerException?
- python - 为什么pyinstaller无法编译python kivi代码
- javascript - 嗨,我正在为我的班级制作一个机器人,需要一些帮助。我有一个嵌入,我希望它被删除 10 秒我该怎么做?不和谐.js 12
- vb.net - 防火墙开启后无法添加规则的IPC解决方案
- android - 即使用户导航离开,也防止 kotlin 协程被中断