optimus
optimus

Reputation: 58

How to extend values in dictionaries using key in Python

How do I extend the values in a dictionary from a list of dictionaries using the keys as the main constraint, say:

d = {'a': (), 'b': 0, 'c': "", d: ""}



l = [ {'a': (23, 48), 'b': 34, 'c': "fame", d: "who"},
      {'a': (94, 29), 'b': 3, 'c': "house", d: "cats"},
      {'a': (23, 12), 'b': 93, 'c': "imap", d: "stack"},
   ]

to give

d = {'a': [(23, 48), (94,29), 23,12], 'b': [34, 3, 94],
      'c': ["fame", "house", "imap"], 'd': ['who', 'cats', 'stack'] }

code used

for i in l:
  d["a"].extend(i.get('a')),
  d["b"].extend(i.get('b')),
  d["c"].extend(i.get('c')),
  d['d'].extend(i.get('d'))

Upvotes: 2

Views: 1359

Answers (2)

blhsing
blhsing

Reputation: 106533

You should initialize d as an empty dict instead, so that you can iterate through l and the key-value pairs to keep appending the values to the sub-list of d at the given keys:

l = [
    {'a': (23, 48), 'b': 34, 'c': "fame", 'd': "who"},
    {'a': (94, 29), 'b': 3, 'c': "house", 'd': "cats"},
    {'a': (23, 12), 'b': 93, 'c': "imap", 'd': "stack"},
]
d = {}
for s in l:
    for k, v in s.items():
        d.setdefault(k, []).append(v)

d becomes:

{'a': [(23, 48), (94, 29), (23, 12)],
 'b': [34, 3, 93],
 'c': ['fame', 'house', 'imap'],
 'd': ['who', 'cats', 'stack']}

If the sub-dicts in l may contain other keys, you can instead initialize d as a dict of empty lists under the desired keys:

l = [
    {'a': (23, 48), 'b': 34, 'c': "fame", 'd': "who"},
    {'a': (94, 29), 'b': 3, 'c': "house", 'd': "cats"},
    {'a': (23, 12), 'b': 93, 'c': "imap", 'd': "stack"},
    {'e': 'choices'}
]
d = {k: [] for k in ('a', 'b', 'c', 'd')}
for s in l:
    for k in d:
        d[k].append(s.get(k))

in which case d becomes:

{'a': [(23, 48), (94, 29), (23, 12), None],
 'b': [34, 3, 93, None],
 'c': ['fame', 'house', 'imap', None],
 'd': ['who', 'cats', 'stack', None]}

Upvotes: 2

TOTO
TOTO

Reputation: 307

You can use defaultdict as follow since the default value is an empty list (https://docs.python.org/2/library/collections.html#collections.defaultdict)


import collections

d = collections.defaultdict(list)
keys = ['a', 'b', 'c', 'd']

for i in l:
    for k in keys:
        d[k].append(i[k])
print(d)

Best regard

Upvotes: 0

Related Questions