-1

I have a python list of dictionaries like this:

[{'George': {u'finance': {u'investing': {u'venture capital': 'Peter'}}}},
 {'George': {u'finance': {u'investing': {u'venture capital': 'John'}}}},
 {'George': {u'finance': {u'investing': {u'venture capital': 'Kate'}}}}]

And I want to groupby so the final results would be:

{'George': {u'finance': {u'investing': {u'venture capital': ['Peter','John','Kate'}}}}

How do i groupby this list of dictionaries ?

Giorgos Perakis
  • 153
  • 2
  • 12
  • Possible duplicate of [Dictionaries of dictionaries merge](http://stackoverflow.com/questions/7204805/dictionaries-of-dictionaries-merge) – tglaria Jan 15 '16 at 12:10
  • I'm pretty sure I've seen this. If the number of dictionaries isn't fixed, then you should use recursion. If not, then you could got to the lowest data, check for differences and merge. – tglaria Jan 15 '16 at 12:11

1 Answers1

1

What have you tried so far?

If the structure of your data is fix as in your example above you could try something like this:

merged_dict = {}
for d in your_list_of_dicts:
    for k in d:
        if k not in merged_dict.keys():
            merged_dict[k] = d[k]
            merged_dict[k]['finance']['investing']['venture capital'] = [merged_dict[k]['finance']['investing']['venture capital']]
        else:
            merged_dict[k]['finance']['investing']['venture capital'].append(d[k]['finance']['investing']['venture capital'])
Benjamin
  • 571
  • 4
  • 8
  • As I see in your try, you take use 'finance' or 'investing' as known. But the truth is that I showed only a small piece of the list. I have numerous different keys and I want to be able to combine them as well. – Giorgos Perakis Jan 18 '16 at 10:56