用另一个词典的一部分更新一个词典

war*_*iuc 7 python

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

dict1['key1'] = dict2['key1']
dict1['key2'] = dict2['key2']
dict1['key3'] = dict2['key3']
Run Code Online (Sandbox Code Playgroud)

dict1用子集更新的类型dict2.

我认为没有一种构建方法可以在表单中执行相同的操作

dict1.update_partial(dict2, ('key1', 'key2', 'key3'))
Run Code Online (Sandbox Code Playgroud)

你通常采取什么方法?你有没有让自己的功能?看起来怎么样?

评论?


我已经提交了主意 Python的思路:

有时你想要一个dict,它是另一个dict的子集.如果dict.items接受了一个可选的键列表,那就太好了.如果没有给出密钥 - 使用默认行为 - 获取所有项目.

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'}
Run Code Online (Sandbox Code Playgroud)

因此,要使用另一个dict的一部分更新dict,您将使用:

dict1.update(dict2.items(['key1', 'key2', 'key3']))
Run Code Online (Sandbox Code Playgroud)

aqu*_*tae 9

你可以这样做:

keys = ['key1', 'key2', 'key3']
dict1.update((k, dict2[k]) for k in keys)
Run Code Online (Sandbox Code Playgroud)


Con*_*ius 6

没有我知道的内置函数,但这将是一个简单的2线程:

for key in ('key1', 'key2', 'key3'):
    dict1 = dict2[key]
Run Code Online (Sandbox Code Playgroud)