Python: Dict Slices
Posted in Journal on Friday, October 15, 2010 12:04AM
Here is a nifty little one line of code I wrote that shows how to slice a dictionary in Python:
# our data
example_dict = {1:"one", 2:"two", 3:"three", }
key_list = (1, 3, )
default = ""
# perform the actual slice here
sliced_dict = dict((k,example_dict.get(k,default)) for k in key_list)
If we print "sliced_dict" we can see we get our desired dictionary slice:
{1:"one", 3:"three", }
This code snippet makes use of Python built in generator expression comprehension to iterate through the key list. The generator builds a list of two item tuples containing key/value pairs. A default is filled in where a key is missing from the source dictionary. Python's handy built in "dict" function converts our list of key/value pair tuples into a dictionary, which then gets assigned as our finished, sliced dictionary.
by virgohippy |


