递归替换或更新嵌套字典中的键值对

问题描述 投票:0回答:2

假设我有一本这样的字典:

mydict = {"name": "Bill", "gender": "Male", "facts": {"age": 20, "location": "England"}}

因此它包含另一个字典作为值。现在假设我有这本字典:

to_replace = {"name": "Billy Kidman", "gender": "Female"}

我想更新

mydict
以反映这一新信息。为此,我使用

from dataclasses import replace
mydict = replace(mydict, **to_replace)

这有效,因为现在看起来像

mydict = {"name": "Billy Kidman", "gender": "Female", "facts": {"age": 20, "location": "England"}}

现在假设我想用以下信息更新

mydict

to_replace_2 = {"name": "Billy Kidman", "gender": "Female", "age": 55}

那么我就不能像上面那样使用替换,因为

age
不是
mydict
的键,但它实际上是值的键。如果我尝试这样做,Python 会抛出错误。我怎样才能正确地做到这一点?我没有
to_replace_2
形式的自由;这就是我上面写的,我无法改变它。有没有办法让替换做我想要它做的事情,找到所有需要替换的键,无论它们是否嵌套并进行更改?

python dictionary nested
2个回答
1
投票

尝试:

def replace(o, to_replace):
    if isinstance(o, dict):
        common_keys = o.keys() & to_replace.keys()
        for k in common_keys:
            o[k] = to_replace[k]

        for v in o.values():
            replace(v, to_replace)

    elif isinstance(o, list):
        for v in o:
            replace(v, to_replace)


mydict = {"name": "Bill", "gender": "Male", "facts": {"age": 20, "location": "England"}}
to_replace_2 = {"name": "Billy Kidman", "gender": "Female", "age": 55}

replace(mydict, to_replace_2)

print(mydict)

打印:

{'name': 'Billy Kidman', 'gender': 'Female', 'facts': {'age': 55, 'location': 'England'}}

1
投票
  • 只需编写一个单独的方法来更新你的字典即可。

  • 关键是首先检查主词典中的

    value
    并查看该值是否是 dict 类型的实例。在这种情况下,您递归调用
    _update()
    并且您的字典将被更新(如果不是)。

代码

def _update(d, new_data):
    for key, value in new_data.items():
        if isinstance(value, dict):
            d[key] = _update(d.get(key, {}), value)
        else:
            d[key] = value
    return d


mydict = {"name": "Bill", "gender": "Male", "facts": {"age": 20, "location": "England"}}
to_replace = {"name": "Billy Kidman", "gender": "Female"}
to_replace_2 = {"name": "Billy Kidman", "gender": "Female", "age": 55}

print(_update(mydict, to_replace))
print(_update(mydict, to_replace_2))


打印

{'姓名': '比利基德曼', '性别': '女', '事实': {'年龄': 20, '地点': '英格兰'}} {'姓名': '比利·基德曼', '性别': '女', '事实':{'年龄':20,'地点':'英格兰'},'年龄':55}

© www.soinside.com 2019 - 2024. All rights reserved.