假设我有一个这样的字典:
d = {27: 32, 28: 41, 29: 29, 30: 29, 31: 67, 32: 65}
还有一个列表:
l = [27, 30, 31]
for n in l:
d2 = {k:v for k,v in d.items() if k in n}
为什么这是不允许的?我可以做什么?
最佳答案
以这种方式得到过滤后的字典就足够了:
d = {27: 32, 28: 41, 29: 29, 30: 29, 31: 67, 32: 65}
l = set([27, 30, 31])
d2 = {k:v for k,v in d.items() if k in l}
print(d2)
输出:
{27: 32, 30: 29, 31: 67}
表达式 ... if k in n
在你的列表理解中迭代 for n in l:
意味着你正在搜索数字中的数字键( number) - 就像我们在 27 中搜索 27
,这在这种情况下毫无意义。
此外,set
对象在大序列的情况下更可取。
Membership testing with sets and dictionaries is much faster, O(1), than searching sequences, O(n)
关于python - 使用列表中的值过滤字典中的键、值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40643461/