Python:如何根据其键的值对字典进行切片?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40440373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:32:14  来源:igfitidea点击:

Python: how to slice a dictionary based on the values of its keys?

pythondictionarykeyslicehashable

提问by FaCoffee

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={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 d1by slicing din such a way that d1contains the following keys: 0, 1, 2, 100, 101, 102. The final output should be:

并且我想d1通过dd1包含以下键的方式切片来创建一个子词典:0, 1, 2, 100, 101, 102. 最终输出应该是:

d1={0:1, 1:2, 2:3, 100:7, 101:8, 102:9}

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.

我认为这个问题适用于所有键是整数的情况,当切片需要遵循某些不等式规则时,以及当最终结果需要将一堆切片放在同一个字典中时。

回答by Olivier Pellier-Cuit

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())}

回答by chepner

One succinct way of creating the sub-dictionary is to use operator.itemgetter. This function takes multiple arguments and returns a new function to return a tuple containing the corresponding elements of a given iterable.

创建子词典的一种简洁方法是使用operator.itemgetter. 这个函数接受多个参数并返回一个新函数来返回一个包含给定迭代的相应元素的元组。

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)))