Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten a dictionary values python

Tags:

python

I have a dictionary in this format.

{'column1': {'id': 'object'},
 'column2': {'mark': 'int64'},
 'column3': {'name': 'object'},
 'column4': {'distance': 'float64'}}

I want this to convert in the format:

{'id': 'object',
 'mark': 'int64',
 'name': 'object',
 'distance': 'float64'}

i.e values of the dictonary in another flattened dictionary.

I tried using :

L= []
for i in d.values():
    L.append(str(i))
dict(L)

But its not working.

like image 368
Shubham R Avatar asked Sep 11 '25 00:09

Shubham R


1 Answers

Use dict-comprehension like this:

>>> my_dict = {'column1': {'id': 'object'},
 'column2': {'mark': 'int64'},
 'column3': {'name': 'object'},
 'column4': {'distance': 'float64'}}
>>> result = {k:v for d in my_dict.values() for k,v in  d.items()}
>>> result
{'distance': 'float64', 'mark': 'int64', 'id': 'object', 'name': 'object'}
like image 131
mshsayem Avatar answered Sep 13 '25 13:09

mshsayem