0

I have a list of dictionary. I need to grow dictionary values under each keys as list in a loop (or any other way).

dl= [{'A':1, 'B':2}, {'A':3, 'B':4}, {'A':5, 'B':6}]
for d in dl:
    ?????

What I need is a dictionary like this:

{'A':[1,3,5], 'B': [2,4,6]}

I need a way without using pandas dataframe. Thanks a lot.

zesla
  • 11,155
  • 16
  • 82
  • 147

3 Answers3

3

with a dictionary, you can use get() and a default value:

dgroups = {}
for d in dl:
    for k, v in d.items():
        dgroups[k] = dgroups.get(k, []) + [v]
print(dgroups)

output:

{'A': [1, 3, 5], 'B': [2, 4, 6]}

or, if you don't mind using a defaultdict:

from collections import defaultdict

dl= [{'A':1, 'B':2}, {'A':3, 'B':4}, {'A':5, 'B':6}]
groups = defaultdict(list)
for d in dl:
    for k, v in d.items():
        groups[k].append(v)
print(groups)

output:

defaultdict(<class 'list'>, {'A': [1, 3, 5], 'B': [2, 4, 6]})
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
0

You can iterate through the list of dicts you have and populate a new empty dictionary with the keys and values from the dicts you have in the list.

final_d = {}


dl= [{'A':1, 'B':2}, {'A':3, 'B':4}, {'A':5, 'B':6}]

for d in dl:
    for key, val in d.items():
        if key not in final_d.keys():
            final_d[key] = []
            final_d[key].append(val)
        else:
            final_d[key].append(val)

print(final_d) 

# Output : {'B': [2, 4, 6], 'A': [1, 3, 5]}

As python dictionaries are not ordered by default, the resultant dict need not be in order. If you want ordered dictionary check OrderedDict from collections module.

Sreeram TP
  • 11,346
  • 7
  • 54
  • 108
0

An implementation in imperative style:

dl= [{'A':1, 'B':2}, {'A':3, 'B':4}, {'A':5, 'B':6}]

result = dict()
for d in dl:
    for dk, dv in d.items():
        arr = result.get(dk, [])
        arr.append(dv)
        result[dk] = arr

An implementation in functional/python style:

from functools import reduce
dl= [{'A':1, 'B':2}, {'A':3, 'B':4}, {'A':5, 'B':6}]

def merge_dicts(m1, m2):
    for k, v in m2.items():
        if k not in m1:
            m1[k] = list()
        m1[k].append(v)
    return m1

result = reduce(lambda prev, curr: merge_dicts(prev, curr), dl, dict())
trunikov
  • 97
  • 1
  • 4