gpt4 book ai didi

python - 深度python字典递归

转载 作者:行者123 更新时间:2023-12-04 12:53:25 25 4
gpt4 key购买 nike

我有一个 python 字典:

d = {
"config": {
"application": {
"payment": {
"dev": {
"modes": {"credit,debit,emi": {}},
"company": {
"address": {
"city": {"London": {}},
"pincode": {"LD568162": {}},
},
"country": {"United Kingdom": {}},
"phone": {"7865432765": {}},
},
"levels": {"0,1,2": {}},
},
"prod": {"modes": {"credit,debit": {}}, "levels": {"0,1": {}}},
}
}
}
}

我想将其更改为这样的(如果值为空{},则将键设为其父级的值)
d = {
"config": {
"application": {
"payment": {
"dev": {
"modes": "credit,debit,emi",
"company": {
"address": {
"city": "London",
"pincode": "LD568162"
},
"country": "United Kingdom",
"phone": "7865432765"
},
"levels": "0,1,2"
},
"prod": {
"modes": "credit,debit",
"levels": "0,1"
}
}
}
}
}
我试图编写代码来遍历这个深度字典,但无法修改它以获得上述输出。请帮忙。
def recur(json_object):
for x in list(json_object.items()):
print(x)
recur(json_object[x])

d={'config': {'application': {'payment': {'dev': {'modes': {'credit,debit,emi': {}}, 'company': {'address': {'city': {'London': {}}, 'pincode': {'LD568162': {}}}, 'country': {'United Kingdom': {}}, 'phone': {'7865432765': {}}}, 'levels': {'0,1,2': {}}}, 'prod': {'modes': {'credit,debit': {}}, 'levels': {'0,1': {}}}}}}}

最佳答案

解决方案1
我们可以使用队列的非递归方法将文档的每个内部/嵌套元素排入队列,如果嵌套值只是 {},则将其作为值放置。 :

# d = ...

queue = [d]

while queue:
data = queue.pop()
for key, value in data.items():
if isinstance(value, dict) and list(value.values()) == [{}]:
data[key] = list(value.keys())[0]
elif isinstance(value, dict):
queue.append(value)

print(d)
输出
{
"config": {
"application": {
"payment": {
"dev": {
"modes": "credit,debit,emi",
"company": {
"address": {
"city": "London",
"pincode": "LD568162"
},
"country": "United Kingdom",
"phone": "7865432765"
},
"levels": "0,1,2"
},
"prod": {
"modes": "credit,debit",
"levels": "0,1"
}
}
}
}
}
解决方案2
这是一个递归方法
# d = ...

def recur(data):
for key, value in data.items():
if isinstance(value, dict) and list(value.values()) == [{}]:
data[key] = list(value.keys())[0]
elif isinstance(value, dict):
recur(value)

recur(d)

print(d)
输出
  • 与解决方案 1 相同
  • 关于python - 深度python字典递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69395834/

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