python:递归地更新字典的值
使用Python3.7,我有一个字典,它的值可以是字符串、字典、字符串列表或字典列表。以下是一个例子:python:递归地更新字典的值,python,string,dictionary,recursion,format,Python,String,Dictionary,Recursion,Format,使用Python3.7,我有一个字典,它的值可以是字符串、字典、字符串列表或字典列表。以下是一个例子: { "about_me": { "age": "{age}" }, "name": { "full_name": { "first": "{first_name}", "last": "{last_name}" } }, "addresses": [{
{
"about_me": {
"age": "{age}"
},
"name": {
"full_name": {
"first": "{first_name}",
"last": "{last_name}"
}
},
"addresses": [{
"home": "{home_address}"
}, {
"work": "{work_address}"
}],
"phones": [
"{home_phone}",
"{work_phone}"
]
}
值在JSON中,如下所示:
{
"{age}": 25,
"{first_name}": "Robert",
"{last_name}": "Miles",
"{home_address}": "123 Main St, CA 90111",
"{work_address}": "456 Wall St, CA 00871",
"{home_phone}": "18008008001",
"{work_phone}": "18008018011"
}
以下是预期的JSON:
{
"about_me": {
"age": "25"
},
"name": {
"full_name": {
"first": "Robert",
"last": "Miles"
}
},
"addresses": [{
"home": "123 Main St, CA 90111"
}, {
"work": "456 Wall St, CA 00871"
}],
"phones": [
"18008008001",
"18008018011"
]
}
例如:
我所要做的就是将这些值递归地注入到“about__me”字典中。示例如下:
person = {
'first':'Robert',
'last': 'Miles',
'age':25
}
print('{first} {last} is {age} years old'.format(**person))
> Robert Miles is 25 years old
到目前为止,我所尝试的对字符串、字典和字典列表都很有用。它在字典字典(xn级别)中分崩离析 您可以将递归与字典理解结合使用:
data = {'about_me': {'age': '{age}'}, 'name': {'full_name': {'first': '{first_name}', 'last': '{last_name}'}}, 'addresses': [{'home': '{home_address}'}, {'work': '{work_address}'}], 'phones': ['{home_phone}', '{work_phone}']}
l = {'{age}': 25, '{first_name}': 'Robert', '{last_name}': 'Miles', '{home_address}': '123 Main St, CA 90111', '{work_address}': '456 Wall St, CA 00871', '{home_phone}': '18008008001', '{work_phone}': '18008018011'}
def update(d):
if not isinstance(d, (dict, list)):
return l.get(d, d)
return {a:update(b) if isinstance(b, dict) else list(map(update, b)) if isinstance(b, list)
else l.get(b, b) for a, b in d.items()}
输出:
{
"about_me": {
"age": 25
},
"name": {
"full_name": {
"first": "Robert",
"last": "Miles"
}
},
"addresses": [
{
"home": "123 Main St, CA 90111"
},
{
"work": "456 Wall St, CA 00871"
}
],
"phones": [
"18008008001",
"18008018011"
]
}
只是为了确保我理解这里的问题。您有一个可以嵌套字符串、列表或其他字典的字典。您想找到一个名为
'abbout me'
的子字典,然后在其中插入一个字典?2个字典:嵌套字典是“about\u me”,而平面字典是“values”。我正试图将“价值观”字典注入“关于我”。希望这有帮助。已确认在@Ajax1234工作。但是曲线球-如果其中一个值是不必映射/替换的静态字符串。。。例如,如果“about_me”有额外的键“status”:“active”(active在“values”字典中不可用)。目前,它给出了一个键错误:“活动”。您可以提出/编辑解决方案吗?@cloudjockey在这种情况下,最好的方法是使用dict.get
。请参阅我最近的编辑。工作正常,但将return l.get(d,d)
替换为return d.format_map(l)
,因为某些字符串可以使用.format_map()例如:home_address
:{home_address}{country}
。与l相同。使用b.format\u map(l)
获取(b,b)
。我最初的问题没有提到它,但使它更一般。我接受了你的回答!
{
"about_me": {
"age": 25
},
"name": {
"full_name": {
"first": "Robert",
"last": "Miles"
}
},
"addresses": [
{
"home": "123 Main St, CA 90111"
},
{
"work": "456 Wall St, CA 00871"
}
],
"phones": [
"18008008001",
"18008018011"
]
}