Reputation: 95
I am beginner with python. I am getting something like following after writing a long block of code using regular expressions. Basically, I am creating dictionaries by using some kind of loops. Dictionary is of same name but only data is different.
my_dict= {'A':{'1':'a','2':'b'}} # created by loop1
my_dict= {'B':{'11':'ab','32':'pb'}} # created by loop2
my_dict= {'C':{'3':'sd','34':'cb'}} # created by loop3
Now as a final dictionary I want to get only one big dictionary which contains all data of above dictionaries. I want this big dictionary because in future I am gonna compare that with other big dictionary.
So my expected result looks like
my_dictionary={'A':{'1':'a','2':'b'} , 'B':{'11':'ab','32':'pb'} , 'C':{'3':'sd','34':'cb'} }
Upvotes: 2
Views: 7090
Reputation: 18123
Just use update():
>>> my_dict= {'C':{'3':'sd','34':'cb'}} # created by loop3
>>> my_big_dict = {}
>>> my_big_dict.update(my_dict)
>>> my_big_dict
{'C': {'3': 'sd', '34': 'cb'}}
Example with a loop:
my_big_dict = {}
for i in range(0, 10):
# create your dict
my_dict= {'A':{'1':'a','2':'b'}}
my_big_dict.update(my_dict)
[{'A':{'1':'a','2':'b'}},
{'A':{'3':'Z'}}]
Use:
dicts = [
{'A':{'1':'a','2':'b'}},
{'B':{'11':'ab','32':'pb'}},
{'C':{'3':'sd','34':'cb'}},
{'A':{'3':'Z'}},
{'C':{'6':'sd','7':'cb'}},
{'A':{'3':'XX'}},]
for d in dicts:
for key, values in d.iteritems():
if my_big_dict.has_key(key):
my_big_dict[key].update(values)
break
my_big_dict.update(d)
print my_big_dict
#=> {'A': {'1': 'a', '3': 'Z', '2': 'b'}, 'C': {'3': 'sd', '6': 'sd', '7': 'cb', '34': 'cb'}, 'B': {'11': 'ab', '32': 'pb'}}
Using just my_big_dict.update(your_dict)
will overwrite the stored dictionary, so you'll need handle the case the the key already exists.
Upvotes: 2
Reputation: 4318
if we assume each dictionary has a counter suffix in its name:
my_dict1= {'A':{'1':'a','2':'b'}} # created by loop1
my_dict2= {'B':{'11':'ab','32':'pb'}} # created by loop2
my_dict3= {'C':{'3':'sd','34':'cb'}} # created by loop3
my_dictionary = dict()
for i in range(0, 3):
my_dictionary.update(eval('my_dict%d' %(i+1)))
Upvotes: 0
Reputation: 31
You can try following. Before entering loop create an empty instance of dictionary.
my_dictionary = dict()
While iterating through the loop just assignee dictionary key / value pairs.
my_dictionary['A'] = {'1':'a','2':'b'}
my_dictionary['B'] = {'11':'ab','32':'pb'}
my_dictionary['C'] = {'3':'sd','34':'cb'}
>>> my_dictionary
{'A': {'1': 'a', '2': 'b'}, 'C': {'3': 'sd', '34': 'cb'}, 'B': {'11': 'ab', '32': 'pb'}}
Upvotes: 1