Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing a dictionary

I have a dictionary, and would like to pass a part of it to a function, that part being given by a list (or tuple) of keys. Like so:

# the dictionary d = {1:2, 3:4, 5:6, 7:8}  # the subset of keys I'm interested in l = (1,5) 

Now, ideally I'd like to be able to do this:

>>> d[l] {1:2, 5:6} 

... but that's not working, since it will look for a key named (1,5). And d[1,5] isn't even valid Python (though it seems it would be handy).

I know I can do this:

>>> dict([(key, value) for key,value in d.iteritems() if key in l]) {1: 2, 5: 6} 

or this:

>>> dict([(key, d[key]) for key in l]) 

which is more compact ... but I feel there must be a "better" way of doing this. Am I missing a more elegant solution?

(I'm using Python 2.7)

like image 941
Zak Avatar asked Mar 23 '15 17:03

Zak


People also ask

Can I slice a dictionary in Python?

With Python, we can easily slice a dictionary to get just the key/value pairs we want. To slice a dictionary, you can use dictionary comprehension. In Python, dictionaries are a collection of key/value pairs separated by commas.

Is Slicing allowed in dictionary?

Slicing a dictionary refers to obtaining a subset of key-value pairs present inside the dictionary. Generally, one would filter out values from a dictionary using a list of required keys. In this article, we will learn how to slice a dictionary using Python with the help of some relevant examples.

How do you slice a dictionary in Javascript?

The slice() method is only avalible on the Array type, and is not avalible on a plain object. To achieve what you require, you could extract the key/value entries of your input object with Object#entries() and then Array#reduce() the reduce the first "n" number of entries to the reduced to the result.

How do you slice a nested dictionary in Python?

Key Points to Remember:Slicing Nested Dictionary is not possible. We can shrink or grow nested dictionary as need. Like Dictionary, it also has key and value. Dictionary are accessed using key.


1 Answers

On Python 3 you can use the itertools islice to slice the dict.items() iterator

import itertools  d = {1: 2, 3: 4, 5: 6}  dict(itertools.islice(d.items(), 2))  {1: 2, 3: 4} 

Note: this solution does not take into account specific keys. It slices by internal ordering of d, which in Python 3.7+ is guaranteed to be insertion-ordered.

like image 138
Cesar Canassa Avatar answered Oct 02 '22 03:10

Cesar Canassa