3

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.

Shubham R
  • 7,382
  • 18
  • 53
  • 119
  • Possible duplicate of [Python: simplest way to get list of values from dict?](https://stackoverflow.com/questions/16228248/python-simplest-way-to-get-list-of-values-from-dict) – Ken Y-N Oct 25 '17 at 05:04

5 Answers5

8

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'}
mshsayem
  • 17,557
  • 11
  • 61
  • 69
1

If you wanted to understand why your current solution does not work, that's because you're looking for a dictionary as the end result, but appending to a list. Inside the loop, call dict.update.

result = {}
for i in data.values():
    result.update(i)

print(result)
{'name': 'object', 'mark': 'int64', 'id': 'object', 'distance': 'float64'}
cs95
  • 379,657
  • 97
  • 704
  • 746
1

This might be the simplest solutions:

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

newColumns = {}
for key, value in columns.items():
  for newKey, newValue in value.items():
    newColumns[newKey] = newValue

print(newColumns)
cs95
  • 379,657
  • 97
  • 704
  • 746
  • 2
    I tend to disagree. I think the `update` is much more succinct, followed by the dict comp shown by the leading answer. – cs95 Oct 25 '17 at 05:19
0

If you get error:

AttributeError: 'int' object has no attribute 'items'

on both answers, and on these solutions, (because your dict is formatted differently), you can use:

newColumns = {}
    for key, value in params.items():
        if isinstance(value,dict):
            for newKey, newValue in value.items():
                newColumns[newKey] = newValue
        else:
            newColumns[key]=value
a.t.
  • 2,002
  • 3
  • 26
  • 66
0

With the dicter library you can easily traverse or flatten each dictionary.

pip install dicter
import dicter as dt

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

# takes the last key with its value
dlist = dt.flatten(d)

# Add each key and value into a new dictionary.
dnew = {}
dt.set_nested(dnew, dlist[0][0], dlist[0][1])
erdogant
  • 1,544
  • 14
  • 23