Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing a dictionary by keys that start with a certain string

This is pretty simple but I'd love a pretty, pythonic way of doing it. Basically, given a dictionary, return the subdictionary that contains only those keys that start with a certain string.

» d = {'Apple': 1, 'Banana': 9, 'Carrot': 6, 'Baboon': 3, 'Duck': 8, 'Baby': 2} » print slice(d, 'Ba') {'Banana': 9, 'Baby': 2, 'Baboon': 3} 

This is fairly simple to do with a function:

def slice(sourcedict, string):     newdict = {}     for key in sourcedict.keys():         if key.startswith(string):             newdict[key] = sourcedict[key]     return newdict 

But surely there is a nicer, cleverer, more readable solution? Could a generator help here? (I never have enough opportunities to use those).

like image 491
Aphex Avatar asked Dec 30 '10 00:12

Aphex


People also ask

How do you slice a dictionary key in 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 Slicing be applied on dictionary?

True or false: Sequence operations such as slicing and concatenation can be applied to dictionaries. Ans: False. A dictionary is not a sequence. Because it is not maintained in any specific order, operations that depend on a specific order cannot be used.

How do I slice a dictionary key?

To slice a dictionary, you can use dictionary comprehension. In Python, dictionaries are a collection of key/value pairs separated by commas. When working with dictionaries, it can be useful to be able to easily access certain elements.

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

How about this:

in python 2.x :

def slicedict(d, s):     return {k:v for k,v in d.iteritems() if k.startswith(s)} 

In python 3.x :

def slicedict(d, s):     return {k:v for k,v in d.items() if k.startswith(s)} 
like image 95
Mark Byers Avatar answered Sep 20 '22 18:09

Mark Byers


In functional style:

dict(filter(lambda item: item[0].startswith(string),sourcedict.iteritems()))

like image 21
seriyPS Avatar answered Sep 18 '22 18:09

seriyPS