Skip to content
Advertisement

Convert a list of objects to a dictionary of lists

I have a list of JSON objects, already sorted (by time let’s say). Each JSON object has type and status. For example:

[
    {'type': 'A', 'status': 'ok'},
    {'type': 'B', 'status': 'ok'},
    {'type': 'A', 'status': 'fail'}
]

I’d like to convert it to:

{
    'A': ['ok', 'fail'],
    'B': ['ok']
}

So of course it’s an easy task but I’m looking for the Pythonic way doing that, so it will spare me a few lines of code

Advertisement

Answer

I don’t know if there is a one-liner but you can make use of setdefault or defaultdict to achieve the desired result as:

data = [
    {'type': 'A', 'status': 'ok'},
    {'type': 'B', 'status': 'ok'},
    {'type': 'A', 'status': 'fail'}
]

Using setdefault():

res = {}
for elt in data:
    res.setdefault(elt['type'], []).append(elt['status'])

Output:

{'A': ['ok', 'fail'], 'B': ['ok']}

Using defaultdict:

from collections import defaultdict
res = defaultdict(list)
for elt in data:
    res[elt['type']].append(elt['status'])

Output:

defaultdict(<class 'list'>, {'A': ['ok', 'fail'], 'B': ['ok']})
Advertisement