erickque
erickque

Reputation: 126

Flatten dictionary of dictionaries

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}]

Upvotes: 2

Views: 1092

Answers (1)

Sunitha
Sunitha

Reputation: 12015

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'}]
>>> 

Upvotes: 7

Related Questions