考虑一下我的字典如下:
{1 => a,2 => b,3 => c,4 => d}
和一个如下所示的列表:
[1,2,3]
是否有一种方法可以返回仅包含
的子字典{1 => a,2 => b,3 => c}
答案 0 :(得分:1)
常规字典理解会这样做:
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'}
有两种处理keys
中不在原始字典中的键的方法:
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'}