gpt4 book ai didi

python - 用另一个字典的一部分更新一个字典

转载 作者:太空狗 更新时间:2023-10-29 21:22:50 25 4
gpt4 key购买 nike

我经常发现自己使用这个结构:

dict1['key1'] = dict2['key1']
dict1['key2'] = dict2['key2']
dict1['key3'] = dict2['key3']

使用 dict2 的子集更新 dict1

我认为没有一个内置的方法可以在表单中做同样的事情

dict1.update_partial(dict2, ('key1', 'key2', 'key3'))

您通常采用什么方法?你有没有为此制定自己的功能?它看起来怎么样?

评论?


我已经提交了 idea到 python 的想法:

有时你想要一个字典,它是另一个字典的子集。如果dict.items 接受一个可选的键列表返回。如果没有 key 给定 - 使用默认行为 - 获取所有项目。

class NewDict(dict):

def items(self, keys=()):
"""Another version of dict.items() which accepts specific keys to use."""
for key in keys or self.keys():
yield key, self[key]


a = NewDict({
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five'
})

print(dict(a.items()))
print(dict(a.items((1, 3, 5))))

vic@ubuntu:~/Desktop$ python test.py
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
{1: 'one', 3: 'three', 5: 'five'}

所以要用另一个字典的一部分更新一个字典,你可以使用:

dict1.update(dict2.items(['key1', 'key2', 'key3']))

最佳答案

你可以这样做:

keys = ['key1', 'key2', 'key3']
dict1.update((k, dict2[k]) for k in keys)

关于python - 用另一个字典的一部分更新一个字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9631331/

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