Friday, June 7, 2013

Merging Python Dictionaries

Sometimes you need to merge two dictionaries into one, and here is a pythonic way of doing it:

>>> x = {'key1': 34, 'key2': 35}
>>> y = {'key3':36', 'key4': 36}
>>> z = x.copy() 
>>> z.update(y)
>>> print z
{'key1': 34, 'key2': 35, 'key3': 36, 'key4': 36}

This method copies the x dictionary into a new set of memory.  This needs to be done because just assigning to a new variable say z = x will reference the same block of memory thus when you update q, you will update dictionary x as well, and we do not want that.  So copy() allocates a new set of memory blocks, puts the information into those blocks, then update() will add the additional keys from an existing dictionary.

It's very simple, and the pythonic way.  (The pythonic way is sort of like the force, but you can move things with your mind or alter thoughts, or do parlor tricks... so it's not like the Force at all)

Enjoy

1 comment:

Anonymous said...

class mydict(dict):
    def __init__(self, d):
        self.dict = d
    def __str__(self):
        return ''.join(str(self.dict))
    def __add__(self, other):
        self.dict.update(other)
        return mydict(self.dict)

x = mydict({'key1': 34, 'key2': 35})
y = {'key3':36, 'key4': 36}

z = x + y
print z

{'key3': 36, 'key2': 35, 'key1': 34, 'key4': 36}