我经常发现自己使用这个结构:
dict1['key1'] = dict2['key1']
dict1['key2'] = dict2['key2']
dict1['key3'] = dict2['key3']
使用字典
dict2
的一个子集来更新 dict1
,这种方式被称为“更新”。我认为没有内置方法可以以此形式进行相同的操作。
dict1.update_partial(dict2, ('key1', 'key2', 'key3'))
你通常采取什么方法?你有自己的函数吗?它是什么样子的?
评论?
我已经向python-ideas提交了一个想法:
有时你需要一个字典是另一个字典的子集。如果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'}
所以要使用另一个字典的一部分来更新字典,您需要使用以下代码:
dict1.update(dict2.items(['key1', 'key2', 'key3']))
dict1.update((k, dict2[k]) for k in keys)
- Duncan