我想使用字典理解或 for 循环清理嵌套字典 python
I want to clean a nested dictionary python using dictionary comprehension or for loops
我有一个包含一系列键的嵌套字典 Dictionary_ABC = {'ABC 1':..., 'ABC 2': ..., ..., 'ABC N':...}。这些密钥中的每一个都包含与 ABC 密钥无关的随机值,但也包含与 ABC 密钥关联的其他值。例如:
Dictionary_ABC['ABC 1'] = {'ABC 1': {'ZYZZ': NONE, 'DAFDZ': NONE, 'EASDF': NONE, 'ABC 1': NONE, ..., 'ABC N': NONE}}
在子字典'ABC 1'中,我想删除所有不包含'ABC 1'的ABC值。所以最终结果应该是这样的:
Dictionary_ABC['ABC 1'] = {'ABC 1': {'ZYZZ': NONE, 'DAFDZ': NONE, 'EASDF': NONE, 'ABC 1': NONE}}
所有其他 ABC # 都应该脱落,我只剩下其他子键和与主键匹配的子键。
我尝试了很多不同的解决方案,但似乎产生最接近结果的是:
Dictionary_ABC_Copy = {}
for key in Dictionary_ABC:
for subkey in Dictionary_ABC[key]:
if this criteria met:
if this next criteria met:
pass #I don't want to copy this
else:
Dictionary_ABC_Copy[key] = subkey #copy if it doesn't fit both criteria
else:
Dictionary_ABC_Copy[key] = subkey #because I want to copy this
条件正在产生必要的结果,但是每当我尝试更新字典或使用上述方法时,字典都会覆盖所有以前的值。如果它们没有传递给过滤条件,我只想用这些值更新键。这是我的第一个问题。
我的第二个问题有更好的方法吗?我希望我已经向 material 提供了帮助回答这些问题所需的信息。
谢谢。
我想你想要这样的东西:
dictionary_abc_copy = {
abc: {k: v for k, v in inner.items() if not k.startwith('ABC ') or k == abc}
for abc, inner in dictionary_abc.items()
}
我有一个包含一系列键的嵌套字典 Dictionary_ABC = {'ABC 1':..., 'ABC 2': ..., ..., 'ABC N':...}。这些密钥中的每一个都包含与 ABC 密钥无关的随机值,但也包含与 ABC 密钥关联的其他值。例如:
Dictionary_ABC['ABC 1'] = {'ABC 1': {'ZYZZ': NONE, 'DAFDZ': NONE, 'EASDF': NONE, 'ABC 1': NONE, ..., 'ABC N': NONE}}
在子字典'ABC 1'中,我想删除所有不包含'ABC 1'的ABC值。所以最终结果应该是这样的:
Dictionary_ABC['ABC 1'] = {'ABC 1': {'ZYZZ': NONE, 'DAFDZ': NONE, 'EASDF': NONE, 'ABC 1': NONE}}
所有其他 ABC # 都应该脱落,我只剩下其他子键和与主键匹配的子键。
我尝试了很多不同的解决方案,但似乎产生最接近结果的是:
Dictionary_ABC_Copy = {}
for key in Dictionary_ABC:
for subkey in Dictionary_ABC[key]:
if this criteria met:
if this next criteria met:
pass #I don't want to copy this
else:
Dictionary_ABC_Copy[key] = subkey #copy if it doesn't fit both criteria
else:
Dictionary_ABC_Copy[key] = subkey #because I want to copy this
条件正在产生必要的结果,但是每当我尝试更新字典或使用上述方法时,字典都会覆盖所有以前的值。如果它们没有传递给过滤条件,我只想用这些值更新键。这是我的第一个问题。
我的第二个问题有更好的方法吗?我希望我已经向 material 提供了帮助回答这些问题所需的信息。
谢谢。
我想你想要这样的东西:
dictionary_abc_copy = {
abc: {k: v for k, v in inner.items() if not k.startwith('ABC ') or k == abc}
for abc, inner in dictionary_abc.items()
}