2

How can I flatten a dictionary of dictonaries in Python, and put them into a list? For example, say I have the following dict:

data = { id1 : {x: 1, y: 2, z: 3}, id2 : {x: 4, y: 5, z: 6}}

How do I get:

[{id: id1, x: 1, y: 2, z: 3}, {id: id2, x: 4, y: 5, z: 6}]
erickque
  • 126
  • 8
  • Possible duplicate of [Flatten nested Python dictionaries, compressing keys](https://stackoverflow.com/questions/6027558/flatten-nested-python-dictionaries-compressing-keys) – Dillanm Jul 16 '18 at 15:33
  • 2
    @Dillanm similar, but not really a duplicate. – John Coleman Jul 16 '18 at 15:38

1 Answers1

7

With python 3.5 and higher

>>> data = { 'id1' : {'x': 1, 'y': 2, 'z': 3}, 'id2' : {'x': 4, 'y': 5, 'z': 6}}
>>> [{**v, 'id':k} for k,v in data.items()]
[{'x': 1, 'y': 2, 'z': 3, 'id': 'id1'}, {'x': 4, 'y': 5, 'z': 6, 'id': 'id2'}]

On older python versions

>>> [dict(v, id=k) for k,v in data.iteritems()]
[{'x': 1, 'y': 2, 'z': 3, 'id': 'id1'}, {'x': 4, 'y': 5, 'z': 6, 'id': 'id2'}]
>>> 
Sunitha
  • 11,777
  • 2
  • 20
  • 23