Convert list of dictionaries to dictionary of dictionaries

Question:

I have a list of dictionaries

ls1 = [{'AccountBalance': '78', 'Status': '0'},
 {'AccountBalance': '56', 'Status': '1'},
 {'AccountBalance': '34', 'Status': '0'},
 {'AccountBalance': '12', 'Status': '0'}]

I would like to convert this to a dictionary of 2 dictionaries

dict1 = {'AccountBalance': {0: '78',
  1: '56',
  2: '34',
  3:  '12'},
    'Status': {0: '0',
  1: '1',
  2: '0',
  3: '0'}}

what would be the fastest way to do this?

pd.DataFrame(ls1).to_dict() works, but I want to know if something is a little faster?

Asked By: frank

||

Answers:

A simple dict comprehension will work too:

new = {
    k: [d[k] for d in ls1]
    for k in ls1[0]
}

No idea about "faster" though.

This creates lists of values, use k: dict(enumerate(d[k] for d in ls1)) if you actually want dicts with numeric keys.

Answered By: gog

You can achieve the same result using Python loops and enumerate. Here’s an example:

my_list = [{'AccountBalance': '78', 'Status': '0'},
       {'AccountBalance': '56', 'Status': '1'},
       {'AccountBalance': '34', 'Status': '0'},
       {'AccountBalance': '12', 'Status': '0'}]

new_dict = {}
for i, d in enumerate(my_list):
    for k, v in d.items():
        new_dict.setdefault(k, {})[i] = v

new_dict will have you’re desired output.

I’m not quite sure how much "faster" this would be, though it’s usually easier working with pandas for very large datasets.

Answered By: Shai V.
from collections import defaultdict

dict1 = defaultdict(dict)
for i, d in enumerate(ls1):
    for k, v in d.items():
        dict1[k][i] = v
        
dict1 = dict(dict1)

Run time is : O(N*M)

  1. N is the number of dictionaries in the original list.
  2. M is the number of key-value pairs in each inner dictionary.
Answered By: newlearner

A one-liner solution would be

dict1 = {key: {index: item[key] for index, item in enumerate(ls1)} for key in ls1[0]}
Answered By: Lahcen YAMOUN
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.