3

I want to join the dictionaries in a list whose key 'user' are the same, but I don't realize how. for example:

[{'count2': 34, 'user': 2},
 {'count4': 233, 'user': 2},
 {'count2': 234, 'user': 4},
 {'count4': 344, 'user': 5}]

would become:

[{'count2': 34, 'count4': 233, 'user': 2 },
 {'count2': 234, 'user': 4},
 {'count4': 344, 'user': 5}]

I searched extensively without found something similar in stack overflow, any help would be greatly appreciated.

4

4 回答 4

7
from collections import defaultdict

dl = [{'count2': 34, 'user': 2},
{'count4': 233, 'user': 2},
{'count2': 234, 'user': 4},
{'count4': 344, 'user': 5}]
print dl

dd = defaultdict(dict)
for d in dl:
    dd[d['user']].update(d)
print dd.values()
于 2012-07-18T16:20:48.233 回答
3

You can sort then use groupby, then merge it

from itertools import groupby
def merge(dicts):
    ret = {}
    for d in dicts:
        ret.update(d)
    return ret

d = [...]
sorted_d = sorted(d, key=lambda x: x['user'])
grouped_d = itertools.groupby(sorted_d, key=lambda x: x['user'])
print [merge(y[1]) for y in grouped]
于 2012-07-18T16:20:10.807 回答
1

In the array:

[{'count2': 34, 'user': 2},
 {'count4': 233, 'user': 2},
 {'count2': 234, 'user': 4},
 {'count4': 344, 'user': 5}]

such that a = {'count2': 34, 'user': 2} and b = {'count4': 233, 'user': 2},

dict(a.items() + b.items())

will return:

{'count2': 34, 'count4': 233, 'user': 2 }

EDIT: Working for groups:

http://codepad.org/ObWT2Hl3

于 2012-07-18T16:06:32.950 回答
1

Something like this should work. But there are probably more efficient ways to do it (and in fewer lines)...

# Input
a=[{'count2': 34, 'user': 2},
 {'count4': 233, 'user': 2},
 {'count2': 234, 'user': 4},
 {'count4': 344, 'user': 5}]

# Get set of unique users
u=list(set([x['user'] for x in a]))

# Create a blank list of dictionaries for the result
r=[{}] * len(u)

# Iterate over input and add the dictionaries together
for x in a:
    r[u.index(x['user'])] = dict(r[u.index(x['user'])].items() + x.items())


>>> r
[{'count2': 34, 'user': 2, 'count4': 233}, {'count2': 234, 'user': 4}, {'count4': 344, 'user': 5}]
于 2012-07-18T16:25:13.237 回答