I want to copy selected elements between dictionaries. Is there a better/more efficient way than this:
dict1 = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4}
list = ['a', 'd']
dict2 = { k : dict1[k] for k in dict1 if k in list }
?
I want to copy selected elements between dictionaries. Is there a better/more efficient way than this:
dict1 = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4}
list = ['a', 'd']
dict2 = { k : dict1[k] for k in dict1 if k in list }
?
就在这里:
dict2 = { k : dict1[k] for k in list }
是的,使用dict.get()
并遍历键列表而不是字典。
>>> {k:dict1.get(k) for k in list1}
{'a': 1, 'd': 4}
请注意,您不应覆盖内置类型list
。
这特别有用,因为如果k
不是 dict1 中的键,则None
返回。
有功能的方式
>>> dict1 = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4}
>>> lst = ['a', 'd']
>>> dict(zip(lst, map(dict1.get, lst)))
{'a': 1, 'd': 4}
或者
>>> from operator import itemgetter
>>> dict(zip(lst, itemgetter(*lst)(dict1)))
{'a': 1, 'd': 4}
但它们比 dict 理解慢 3 倍 :)