Python:递归地更改字典

时间:2013-12-21 15:14:29

标签: python dictionary

我对Python中的字典有疑问。

我有这样的字典:

D = {'key1' : ['key3'], 'key2' : {}, 'key3' : ['key2']}

我的目标是尽可能地替换所有值:

After first iteration:
D = {'key1' : {'key3' : ['key2']}, 'key2' : {}, 'key3' : {'key2' : {}]}

After second iteration:
D = {'key1' : {'key3' : {'key2' : {}}}, 'key2' : {}, 'key3' : ['key2']}

有可能吗?

我想到这样的事情:

for k in D.keys():
    try:
        if D[k] in D.keys:
            D[k] = D[D[k]]
    except:
        pass

我知道这不正确而且不起作用。我想也许我应该使用递归函数。 你能告诉我怎样才能正确更新字典中的值?

很抱歉,如果我的解释不明确,但我希望你明白这一点。

谢谢!

2 个答案:

答案 0 :(得分:1)

您需要确保替换最浅的部分,即d中密钥的值已经是dict的部分,首先:

def fix_dict(d):
    fixed = False
    while not fixed:
        fixed = True
        for k, v in d.items():
            if isinstance(v, list) and isinstance(d[v[0]], dict):
                fixed = False
                d[k] = {v[0]: d[v[0]]}

请注意,这是递归,但会循环,直到它执行没有任何更改的传递,并且不限于两层嵌套。

答案 1 :(得分:0)

这将为您提供解决方案,但我不是Python程序员,因此可能有更好的方法:

D = {'key1' : ['key3'], 'key2' : {}, 'key3' : ['key2']}

def sub(D, d):
  if isinstance(d, list) and d[0] in D:
    d = {d[0] : sub(D, D[d[0]])}
  return d

for k in D.keys():
  D[k] = sub(D, D[k])

print D

输出:

{'key3': {'key2': {}}, 'key2': {}, 'key1': {'key3': {'key2': {}}}}