的一部分的字典,我经常用这个结构发现自己:用dict2
一个子集更新dict1
的更新与另一个字典
dict1['key1'] = dict2['key1']
dict1['key2'] = dict2['key2']
dict1['key3'] = dict2['key3']
类。
我觉得没有在形式
什么方法,你通常需要做同样的事情内置的方法?你有没有为此做出自己的功能?它看起来像什么?
评论?
我已经提交了idea Python的思路:
有时候你想要的字典这是另一个字典的子集。这将很好,如果 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))))
[email protected]:~/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']))
我学到了什么新东西 - 真的没有任何捷径......我喜欢这个答案 - 它更加明确。我认为它比aquavitae的答案快,因为它不会创建任何中间列表或生成器。 – warvariuc 2012-03-09 12:56:50