Extract sub dictionary from keys that appear in a given list
本问题已经有最佳答案,请猛点这里访问。
我有一本像这样的字典:
_1=>A,2=>B,3=>C,4=>D_
一个列表如下:
〔1, 2, 3〕
有没有只返回包含
1=>A,2=>B,3=>C
常规的听写理解可以做到这一点:
1 2 3 4 5 | d = {1: 'a', 2: 'b', 3: 'c', 4: 'd'} keys = [1, 2, 3] dct = {key: d[key] for key in keys} print(dct) # {1: 'a', 2: 'b', 3: 'c'} |
在
1 2 3 4 5 6 7 8 9 | keys = [1, 2, 3, 7] # default value None dct = {key: d[key] if key in d else None for key in keys} print(dct) # {1: 'a', 2: 'b', 3: 'c', 7: None} # ignore the key if it is not in the original dict dct = {key: d[key] for key in set(keys).intersection(d.keys())} print(dct) # {1: 'a', 2: 'b', 3: 'c'} |