Python: Dict Slices

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.

Comments

  • Ken Williams | Thursday, July 21, 2011 05:40PM

    Obligatory Perl equivalent:

    %sliced_dict = map {$_, $example_dict{$_}} @key_list;

    Or if you prefer, using actual slices:

    @sliced_dict{@key_list} = @example_dict{@key_list};

    I found your page hoping for a nice notation for a dict slice (I'm not a very good Python programmer), but I guess only constructor invocations are possible.

Post a Comment