Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert or update keys in a python dictionary

I have a python dictionary dict1 with more than 20,000 keys and I want to update it with another dictionary dict2. The dictionaries look like this:

dict1
  key11=>[value11]
  key12=>[value12]
  ...
  ...
  keyxyz=>[value1x]      //common key
  ...... so on

dict2
  key21=>[value21]
  key22=>[value22]
  ...
  ...
  keyxyz=>[value2x]      // common key
  ........ so on

If I use

dict1.update(dict2)

then the keys of dict1 which are similar to keys of dict2 will have their values overwritten by values of dict2. What I want is if a key is already present in dict1 then the value of that key in dict2 should be appended to value of dict1. So

dict1.conditionalUpdate(dict2)

should result in

dict1
  key11=>[value11]
  key12=>[value12]
  key21=>[value21]
  key22=>[value22]
  ...
  ...
  keyxyz=>[value1x,value2x]

A naive method would be iterating over keys of dict2 for each key of dict1 and insert or update keys. Is there a better method? Does python support a built in data structure that supports this kind of functionality?

like image 905
lovesh Avatar asked May 17 '12 11:05

lovesh


1 Answers

Use defaultdict from the collections module.

>>> from collections import defaultdict
>>> dict1 = {1:'a',2:'b',3:'c'}
>>> dict2 = {1:'hello', 4:'four', 5:'five'}
>>> my_dict = defaultdict(list)
>>> for k in dict1:
...    my_dict[k].append(dict1[k])
...
>>> for k in dict2:
...    my_dict[k].append(dict2[k])
...
>>> my_dict[1]
['a', 'hello']
like image 126
Burhan Khalid Avatar answered Sep 19 '22 15:09

Burhan Khalid