gpt4 book ai didi

python - 在 Python 中递归地转换字典

转载 作者:太空狗 更新时间:2023-10-30 01:26:26 25 4
gpt4 key购买 nike

这是一本字典:

data = {
'a': {
'b': {
'c': {
'd': {
'e': {
'f': 1,
'g': 50,
'h': [1, 2, 4],
'i': 3,
'j': [7, 9, 6],
'k': [
[('x', 'abc')],
[('y', 'qwe')],
[('z', 'zxc')]
]
}
}
}
}
}
}

我的目标是尽可能找到值并将其转换为字典:

data = {
'a': {
'b': {
'c': {
'd': {
'e': {
'f': 1,
'g': 50,
'h': [1, 2, 4],
'i': 3,
'j': [7, 9, 6],
'k': [{
'x': 'abc'
}, {
'y': 'qwe'
}, {
'z': 'zxc'
}]
}
}
}
}
}
}

我认为这可以使用递归来完成,我什至写了一个,但它不起作用。

def f(d):
for key, value in d.iteritems():
if type(d[key]) is dict:
f(d)

try:
d[key] = dict(d[key])
except:
if type(d[key]) is list:
for i in d[key]:
try:
d[key][i] = dict(d[key][i])
except:
pass

return d

错误:

RecursionError: maximum recursion depth exceeded while calling a Python object

如何让它发挥作用?

如果你能提供一个不用递归的解决方案,我也很乐意得到它。

最佳答案

你的程序中有一堆错误,让我们检查它们并提出一个工作版本。

def f(d):
for key, value in d.iteritems():
if type(d[key]) is dict:
f(d) # You should call d[key] instead
try:
d[key] = dict(d[key]) # Never assign an object back to the one you are iterating over, create a new object instead.
except:
if type(d[key]) is list:
for i in d[key]:
try:
d[key][i] = dict(d[key][i]) # This doesn't work, can't convert a tuple/list this way.
except:
pass

return d

这是带有两个递归函数的代码的更正版本。一个用于列表,另一个用于字典。

def f1(value):
e = []
for val in value:
if type(val) is list:
e += f1(val) # Append list to current list
elif type(val) is tuple:
e.append({val[0]: val[1]}) # Convert tuple to dictionary
else:
e.append(val) # Append normal list values normally
return e

def f(d, e = {}):
for key, value in d.iteritems():
if type(value) is dict:
e[key] = f(value, {}) # Recurse for dictionaries
elif type(value) is list:
e[key] = f1(value) # Call the other recursive function for list
else:
e[key] = value # Otherwise like strings and ints just append
return e

在这里测试:https://repl.it/LDKn/0

关于python - 在 Python 中递归地转换字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46181365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com