Reputation: 78254
I have a nested dict that looks like the below. How do I flatten that so there is a row for each botten level as a list of lists?
e.g
[[en,Chome,ChromeOS,null,180, '0', '0', '0', '0',
[en, Linux,null,27868, '0', '0', '0', '0'],
...
]
input
test = {u'en': {'Chrome': {'ChromeOS': {u'null': [180, '0', '0', '0', '0']},
'Linux': {u'null': [27868, '0', '0', '0', '0']},
'Macintosh': {u'null': [330991, '0', '0', '0', '0']},
'Windows': {u'null': [3296819, '0', '0', '0', '0']}},
'Firefox': {'Linux': {u'null': [18076, '0', '0', '0', '0']},
'Macintosh': {u'null': [168444, '0', '0', '0', '0']},
'Windows': {u'null': [1517775, '0', '0', '0', '0']}},
'Konqueror': {'Linux': {u'null': [9, '0', '0', '0', '0']}},
'Microsoft Internet Explorer': {'Windows': {u'null': [3060154,
'0',
'0',
'0',
'0']}},
'Opera': {'Linux': {u'null': [2274, '0', '0', '0', '0']},
'Macintosh': {u'null': [1573, '0', '0', '0', '0']},
'Windows': {u'null': [38589, '0', '0', '0', '0']}},
'Opera Mobile': {'Linux': {u'null': [5807, '0', '0', '0', '0']},
'Windows': {u'null': [1, '0', '0', '0', '0']}},
'Safari': {'Blackberry': {u'null': [530, '0', '0', '0', '0']},
'Linux': {u'null': [292862, '0', '0', '0', '0']},
'Macintosh': {u'null': [618641, '0', '0', '0', '0']},
'Windows': {u'null': [36359, '0', '0', '0', '0']}},
'SeaMonkey': {'Linux': {u'null': [120, '0', '0', '0', '0']},
'Macintosh': {u'null': [224, '0', '0', '0', '0']},
'Windows': {u'null': [1890, '0', '0', '0', '0']}},
'WOSBrowser': {'Linux': {u'null': [687, '0', '0', '0', '0']}},
'null': {'null': {u'null': [15559, '0', '0', '0', '0']}}}}
Upvotes: 3
Views: 4635
Reputation: 5933
If the terminal node is not a list, then you should "yield [v]" instead of "yield v".
Upvotes: 0
Reputation: 304147
def flatten_dict(d):
for k,v in d.items():
if isinstance(v, dict):
for item in flatten_dict(v):
yield [k]+item
else:
yield v
flattened = list(flatten_dict(test))
Upvotes: 9