0

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
  • 6,554
  • 15
  • 48
  • 106
  • 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

3 Answers3

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
  • 16,985
  • 11
  • 60
  • 67
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
  • 330,695
  • 80
  • 606
  • 657
0

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
  • 330,695
  • 80
  • 606
  • 657
  • 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