【发布时间】:2020-06-22 13:33:32
【问题描述】:
我在更新嵌套字典中的值时遇到了一些问题。
my_dic = {'TypeA': {'Bit0': {'TypeA': {'Bit0': 'A', 'Bit1': 'B', 'Bit2' : 'C'}, 'TypeB': 'D', 'TypeC': 'E'}, 'Bit1': 'F', 'Bit2': 'G'}, 'TypeB': 'H'}
我需要用新字典更新具有值 A、B 和 C 的字典
new_dic = {Sensor Error: {'Bit0' : 'X', 'Bit1': 'Y', 'Bit2': 'Z'}}
我不想要一个新功能来做这件事。这出现在我需要更新字典的处理中的某个地方。这可以使用while循环或for循环来完成吗?经历了其他堆栈溢出问题。找不到这样的东西。所有这些问题都有一个功能,并且最多在字典的两层内迭代。字典在这里可以有任何深度。
def recursive_lookup(k, d):
if k in d: return d[k]
for v in d.values():
if isinstance(v, dict):
a = recursive_lookup(k, v)
if a is not None: return a
return None
尝试了这段代码,发现这对任何深度都不起作用。另外,这不符合我的要求。我不需要函数来查找键并替换它的值。
详细来说,字典基本上都是错误和错误词。
my_dic = {
'System Error': {
'Bit0': 'Out of Sync'
'Bit1': {
'Sensor Error':{
'Bit0': 'Out of Range Error'
'Bit1': 'Communication Error'
}
}
'Bit2': 'System Unresponsive Error'
}
}
这是my_dic的应用
期望的输出是:
my_dic = {
'System Error': {
'Bit0': 'Out of Sync'
'Bit1': {
'Sensor Error':{
'Bit0': 'X'
'Bit1': 'Y'
'Bit2': 'Z'
}
}
'Bit2': 'System Unresponsive Error'
}
}
【问题讨论】:
-
您能解释一下
new_dic是如何生成的吗? -
听起来你需要一个递归函数来深入你的数据结构。
-
我不确定我是否完全理解了这个问题,为什么
my_dic['TypeA']['Bit0']['TypeA'] = new_dic不起作用? -
我不想那样硬编码。有一个文件,我从中创建了这本字典。文件中的数据可能会更改,并且深度可能会有所不同。我想以通用的方式处理它。 @CoryNezin
-
为什么会出现“我不想要一个新功能这样做”的限制?没有函数就不能有递归函数。 :)
标签: python python-2.7 dictionary