Python Tip: Tricks for Dict(ionarie)s


nathanieltroutman - Posted on 06 November 2008

Okay, so things everyone should know about dictionaries, they are in the python manual but I still didn't know them until today. First off creating a dictionary in the code (ie hardcoded)

d = dict(one=2, two=3)

This is a simpler way of doing things, and it sure beats having to rember all your quotes when doing:

d = {'one': 2, 'two': 3}

Granted the second way looks cooler! But we have to make compromises. Another cool thing, is taking a list of keys and list of values and turning them into a dictionary:

keys = ('one', 'two')
values = (2, 3)
d = dict(zip(keys, values))

Which is a compact way of doing this (which is what I did before I read the previous way):

keys = ('one', 'two')
values = (2, 3)
d = dict(map(lambda k,v: (k,v), keys, values))

The map and lambda works, but its not nearlly as clean, though understanding what zip does is a kinda hard just reading the manual, it really needs some examples to straighten things out. These were intially prompted when I wanted a blankslate PHP like object:

class objectify(dict):
    def __init__(self, values, keys):
        self.__dict__ = self
        map(self.__setitem__, keys, values)

Which lets us do nifty things like:

keys = ('one', 'two')
values = (2, 3)
o = objectify(values, keys)
o.three = o.one + o.two

And thats that for fun little dictionary tips.

Post new comment

The content of this field is kept private and will not be shown publicly.
By submitting this form, you accept the Mollom privacy policy.