Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of dicts to/from dict of lists

I am looking to change back and forth between a dictionary of lists (all of the same length):

DL = {'a': [0, 1], 'b': [2, 3]} 

and a list of dictionaries:

LD = [{'a': 0, 'b': 2}, {'a': 1, 'b': 3}] 

I am looking for the cleanest way to switch between the two forms.

like image 742
Adam Greenhall Avatar asked Apr 05 '11 20:04

Adam Greenhall


People also ask

How do I convert a list of dictionaries in Python?

Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.

Is Dict better than list?

It is more efficient to use a dictionary for lookup of elements because it takes less time to traverse in the dictionary than a list. For example, let's consider a data set with 5000000 elements in a machine learning model that relies on the speed of retrieval of data.

Can a dict have a list?

In this program, we will discuss how to create a dictionary of lists. In Python, the dictionary of lists means we have to assign values as a list. In Python dictionary, it is an unordered and immutable data type and can be used as a keys element.


2 Answers

For those of you that enjoy clever/hacky one-liners.

Here is DL to LD:

v = [dict(zip(DL,t)) for t in zip(*DL.values())] print(v) 

and LD to DL:

v = {k: [dic[k] for dic in LD] for k in LD[0]} print(v) 

LD to DL is a little hackier since you are assuming that the keys are the same in each dict. Also, please note that I do not condone the use of such code in any kind of real system.

like image 92
Andrew Floren Avatar answered Sep 28 '22 04:09

Andrew Floren


If you're allowed to use outside packages, Pandas works great for this:

import pandas as pd pd.DataFrame(DL).to_dict(orient="records") 

Which outputs:

[{'a': 0, 'b': 2}, {'a': 1, 'b': 3}] 

You can also use orient="list" to get back the original structure

{'a': [0, 1], 'b': [2, 3]} 
like image 26
eric chiang Avatar answered Sep 28 '22 03:09

eric chiang