[英]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}
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
. 我想通过切片
d
创建一个子字典d1
,使得d1
包含以下键: 0, 1, 2, 100, 101, 102
。 The final output should be: 最终输出应该是:
d1={0:1, 1:2, 2:3, 100:7, 101:8, 102:9}
Is there an efficient Pythonic way of doing this, given that my real dictionary contains over 2,000,000 items? 考虑到我的真实字典包含超过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}
In python 2.7 you can also compute keys with (in python 3.x replace it.ifilter(...)
by filter(...)
): 在Python 2.7,你还可以计算与键(在python 3.x的替代
it.ifilter(...)
通过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())}
One succinct way of creating the sub-dictionary is to use operator.itemgetter
. 创建子字典的一种简洁方法是使用
operator.itemgetter
。 This function takes multiple arguments and returns a new function to return a tuple containing the corresponding elements of a given iterable. 此函数接受多个参数并返回一个新函数以返回包含给定iterable的相应元素的元组。
from operator import itemgetter as ig
k = [0, 1, 2, 100, 101, 102]
# ig(0,1,2,100,101,102) == lambda d : (d[0], d[1], d[2], d[100], d[101], d[102])
d1 = dict(zip(k, ig(*k)(d)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.