Python: how to slice a dictionary based on the values of its keys?
Solution 1
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(...)
):
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())}
Solution 2
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.
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)))
Related videos on Youtube
![FaCoffee](https://i.stack.imgur.com/TVsCr.png?s=256&g=1)
FaCoffee
NHL Winnipeg Jets fan - GO JETS GO! Getting a lot of valuable help here. For DOWN VOTERS: if you are going to down vote, tell the recipient why you are doing so - this way he/she can actually make improvements and gain confidence. Improductive critics should be banned.
Updated on July 09, 2022Comments
-
FaCoffee almost 2 years
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 slicingd
in such a way thatd1
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}
Is there an efficient Pythonic way of doing this, given that my real dictionary contains over 2,000,000 items?
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.
-
flybonzai over 7 yearsYou can't really "slice" a dictionary, since it's a mutable mapping and not a sequence. I think dict comprehension is your best bet.
-
-
FaCoffee over 7 yearsWell, I should have pointed this out in the first place. While it is true that I know what the needed keys, they are too many to be put explicitly in a tuple. Is there a way to construct the tuple using inequality rules?
-
Moinuddin Quadri over 7 years@CF84: What is you definition of the inequality rule? Please share the complete info, we can not read your mind :)
-
FaCoffee over 7 yearsOne definition could be to "draft" all values which keys are greater than and smaller than a certain value
x
. Example:06010001 < x <= 06012000
. -
Olivier Pellier-Cuit over 7 yearssee my updated answer. With python 3.x you just have to replace it.filter(...) by filter(...)