【发布时间】:2021-10-08 18:00:24
【问题描述】:
也许这是不可能的,但如果没有通过给定字典中每个键的 for 循环,则根据字典中的键合并两者
给定:
dict1 = { 'APPL' : { 'cp': 1, 'sed': 'bull'}, 'BAC' : { 'cp': 1, 'sed': 'bull'}}
dict2 = { 'APPL' : { 'tp': 100}}
dict3 = dict1 | dict2 ## python ≥3.9 only
print(dict3)
{'APPL': {'tp': 100}, 'BAC': {'cp': 1, 'sed': 'bull'}}
dict1.update(dict2)
print(dict1)
{'APPL': {'tp': 100}, 'BAC': {'cp': 1, 'sed': 'bull'}}
期望的输出
{'APPL': {'tp': 100,'cp': 1, 'sed': 'bull'}, 'BAC': {'cp': 1, 'sed': 'bull'}}
我现在可以用 for 循环来做,只是想知道是否有更优雅的解决方案
【问题讨论】:
-
this 或许就是您要找的东西
-
你愿意使用 pandas 吗?没有循环,它不会(如你所说)优雅,只会是硬编码。
-
是否存在根密钥不包含另一个字典的风险,或者存在两个以上级别的字典?
标签: python json dictionary python-3.9