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.
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.
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.
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.
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.
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]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With