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).
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.
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.
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.
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.
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)}
In functional style:
dict(filter(lambda item: item[0].startswith(string),sourcedict.iteritems()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With