sai
sai

Reputation: 139

Merging dictionaries with same keys

I wrote some python code to pull data from SQL server and I'm currently trying to merge the data. I tried to pull the data into a Dataframe and then work with it, but wasn't able to do that.

The current form that I set the data up as is like this :

[ { a : { 1 : ( x,y,z,...) }}, 
{ a : { 2 : ( x,y,z,...) }},
{ a : { 3 : ( x,y,z,...) }} ]

This is where I want to get to

[ { a : { 1 : ( x,y,z,...) , 2 : (x,y,...) , 3 : (x,y,z,...) } ]

Upvotes: 0

Views: 79

Answers (3)

Sunny Patel
Sunny Patel

Reputation: 8078

You can make use of the reduce function and dict.update to transform the data. Assuming that 'a' is your only key, you can do this:

a = [
  {'a': {1: (1, 2, 3)}},
  {'a': {2: (4, 5, 6)}},
  {'a': {3: (7, 8, 9)}}
]

def update(d, c):
  d['a'].update(c['a'])
  return d
print reduce(update, a, {'a':{}}) #Prints {'a': {1: (1, 2, 3), 2: (4, 5, 6), 3: (7, 8, 9)}}

Upvotes: 0

Alex Hall
Alex Hall

Reputation: 36013

How's this?

data = [{'a': {1: 4}, 'b': {7: 8}},
        {'a': {2: 5}, 'b': {9: 10}},
        {'a': {3: 6}}]
all_keys = set().union(*data)
result = {}
for key in all_keys:
    result[key] = {}
    for d in data:
        if key in d:
            result[key].update(d[key])

print(result)  # {'b': {7: 8, 9: 10}, 'a': {1: 4, 2: 5, 3: 6}}

Upvotes: 1

jpp
jpp

Reputation: 164623

Use a nested dictionary structure via collections.defaultdict.

Note that in this implementation duplicate inner keys are not permitted; for example, you cannot have two dictionaries with outer key 'a' and inner key 1. In this case, the last will take precedence.

from collections import defaultdict

lst = [ { 'a' : { 1 : ( 3, 4, 5 ) }}, 
        { 'a' : { 2 : ( 6, 7, 8 ) }},
        { 'a' : { 3 : ( 1, 2, 3 ) }},
        { 'c' : { 4 : ( 5, 9, 8 ) }}, 
        { 'b' : { 1 : ( 6, 6, 8 ) }},
        { 'c' : { 3 : ( 2, 5, 7 ) }}]

d = defaultdict(dict)

for item in lst:
    key = next(iter(item))
    d[key].update(item[key])

# defaultdict(dict,
#             {'a': {1: (3, 4, 5), 2: (6, 7, 8), 3: (1, 2, 3)},
#              'b': {1: (6, 6, 8)},
#              'c': {3: (2, 5, 7), 4: (5, 9, 8)}})

Upvotes: 2

Related Questions