Python:如何根据其键值对字典进行切片? [英] Python: how to slice a dictionary based on the values of its keys?
问题描述
说我有一本这样的字典:
Say I have a dictionary built like this:
d={0:1, 1:2, 2:3, 10:4, 11:5, 12:6, 100:7, 101:8, 102:9, 200:10, 201:11, 202:12}
,我想通过切片d
来创建子词典d1
,使d1
包含以下键:0, 1, 2, 100, 101, 102
.最终输出应为:
and I want to create a subdictionary d1
by slicing d
in such a way that d1
contains the following keys: 0, 1, 2, 100, 101, 102
. The final output should be:
d1={0:1, 1:2, 2:3, 100:7, 101:8, 102:9}
鉴于我的真实词典包含超过2,000,000个项目,是否有一种有效的Pythonic方法?
我认为这个问题适用于所有键都是整数的情况,当切片需要遵循某些不等式规则,并且最终结果需要将一堆切片放在同一块中时字典.
I think this question applies to all cases where keys are integers, when the slicing needs to follow certain inequality rules, and when the final result needs to be a bunch of slices put together in the same dictionary.
推荐答案
您可以通过以下方式使用字典理解:
You could use dictionary comprehension with:
d = {0:1, 1:2, 2:3, 10:4, 11:5, 12:6, 100:7, 101:8, 102:9, 200:10, 201:11, 202:12}
keys = (0, 1, 2, 100, 101, 102)
d1 = {k: d[k] for k in keys}
在python 2.7中,您还可以使用(在python 3.x中将it.ifilter(...)
替换为filter(...)
)来计算密钥:
In python 2.7 you can also compute keys with (in python 3.x replace it.ifilter(...)
by filter(...)
):
import itertools as it
d = {0:1, 1:2, 2:3, 10:4, 11:5, 12:6, 100:7, 101:8, 102:9, 200:10, 201:11, 202:12}
d1 = {k: d[k] for k in it.ifilter(lambda x: 1 < x <= 11, d.keys())}
这篇关于Python:如何根据其键值对字典进行切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!