Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 551
FaCoffee Avatar asked Nov 05 '16 16:11

FaCoffee


People also ask

How do you slice a value in a dictionary Python?

Given dictionary with value as lists, slice each list till K. Input : test_dict = {“Gfg” : [1, 6, 3, 5, 7], “Best” : [5, 4, 2, 8, 9], “is” : [4, 6, 8, 4, 2]}, K = 3 Output : {'Gfg': [1, 6, 3], 'Best': [5, 4, 2], 'is': [4, 6, 8]} Explanation : The extracted 3 length dictionary value list.

Can we access the keys from values in dictionary Python?

We can also fetch the key from a value by matching all the values using the dict. item() and then print the corresponding key to the given value.

How do you separate a key from a value in a dictionary?

Creating a Dictionary To do that you separate the key-value pairs by a colon(“:”). The keys would need to be of an immutable type, i.e., data-types for which the keys cannot be changed at runtime such as int, string, tuple, etc. The values can be of any type.


2 Answers

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())}
like image 191
Olivier Pellier-Cuit Avatar answered Sep 21 '22 16:09

Olivier Pellier-Cuit


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)))
like image 39
chepner Avatar answered Sep 17 '22 16:09

chepner