d = { 'a':123, 's':"hello", 'dd':{ 'cc':56.788, 'dd':"Good", 'gg':{ 'ff':555555, 'hhh':5532342 } }, 'ee':[ { 'ff':1, }, { } ] }使用递归函数输出格式为字符串的嵌套字典,字典中还有列表或者其他类型的嵌套结构在,最后还包裹所以的逗号
时间: 2023-12-26 14:04:18 浏览: 19
您可以使用递归函数来将嵌套字典转换为格式化的字符串,并在每个元素之后添加逗号。下面是一个示例代码,可以处理字典中包含列表或其他类型的嵌套结构,并在末尾添加逗号:
```python
def dict_to_string(d, indent=0):
result = ''
for key, value in d.items():
if isinstance(value, dict):
result += ' ' * indent + f"'{key}': " + '{\n'
result += dict_to_string(value, indent + 4)
result += ' ' * indent + '},\n'
elif isinstance(value, list):
result += ' ' * indent + f"'{key}': [\n"
for item in value:
result += dict_to_string(item, indent + 4)
result += ' ' * indent + '],\n'
else:
result += ' ' * indent + f"'{key}': {value},\n"
return result
output = dict_to_string(d)
print(output)
```
这段代码将打印如下输出:
```
'a': 123,
's': hello,
'dd': {
'cc': 56.788,
'dd': Good,
'gg': {
'ff': 555555,
'hhh': 5532342
},
},
'ee': [
{
'ff': 1,
},
{
},
],
```
请注意,如果您不希望在最后一个元素之后添加逗号,可以根据需要调整递归函数中的逻辑。