问题
I have a dictionary
-
d={'revenues':
{
'201907':
{'aaa.csv':'fdwe34x2'},
'201906':{'ddd.csv':'e4c5q'}
},
'complaints':
{'2014':
{'sfdwa.csv','c2c2jh'}
}
}
I want to convert it into list
of tuples
-
[
('revenues','201907','aaa.csv','fdwe34x2'),
('revenues','201906','ddd.csv','e4c5q'),
('complaints','2014','sfdwa.csv','c2c2jh')
]
I tried using list comprehensions
, but did not help -
l = [(k,[(p,q) for p,q in v.items()]) for k,v in d.items()]
print(l)
[('revenues', [('201907', {'aaa.csv': 'fdwe34x2'}), ('201906', {'ddd.csv': 'e4c5q'})]),
('complaints', [('2014', {'c2c2jh', 'sfdwa.csv'})])]
Any suggestions?
回答1:
If you're not sure how many levels this list may have, it seems that what you need is recursion:
def unnest(d, keys=[]):
result = []
for k, v in d.items():
if isinstance(v, dict):
result.extend(unnest(v, keys + [k]))
else:
result.append(tuple(keys + [k, v]))
return result
Just a friendly reminder: before Python 3.6, dict order is not maintained.
[('complaints', '2014', 'sfdwa.csv', 'c2c2jh'),
('revenues', '201906', 'ddd.csv', 'e4c5q'),
('revenues', '201907', 'aaa.csv', 'fdwe34x2')]
回答2:
You can loop through the levels of your dictionary:
[(x, y, z) for x in d for y in d[x] for z in d[x][y]]
来源:https://stackoverflow.com/questions/57627575/convert-a-nested-dictionary-into-list-of-tuples