Reputation: 21
I have a nested dict that looks like:
{KeyA: {'ItemA': 1, 'ItemB': 2, 'ItemC': 3, 'ItemD': 4, 'ItemE': 5, 'ItemF': 6},
{KeyB: {'ItemR': 2, 'ItemQ': 3, 'ItemG': 4, 'ItemZ': 5, 'ItemX': 6, 'ItemY': 7}
I would like to output this to a csv where the desired row format is:
ItemA, 1, Item B, 2, ItemC, 3, ItemD, 4, ItemE, 5, ItemF, 6
I've managed to get a row that's keys and then another below it with the associated value with the below code:
for item in myDict:
item = myDict[x]
itemVals = item.values()
wr.writerow(item)
wr.writerow(itemVals)
x += 1
I've tried a number of ways of reformatting this and keep running into subscriptable errors every which way I try.
The length of the top level dict could be large, up to 30k nested dicts. The nested dicts are a constant length of 6 key:value pairs, currently.
What's a clean way to achieve this?
Upvotes: 2
Views: 66
Reputation: 1627
Here is an implementation with loops:
myDict = {'KeyA': {'ItemA': 1, 'ItemB': 2, 'ItemC': 3, 'ItemD': 4, 'ItemE': 5, 'ItemF': 6},
'KeyB': {'ItemR': 2, 'ItemQ': 3, 'ItemG': 4, 'ItemZ': 5, 'ItemX': 6, 'ItemY': 7}}
with open("output.csv", "w") as file:
for key in myDict:
for nestedKey in myDict[key]:
file.write(key + "," + str(myDict[key][nestedKey]) + ",")
file.write("\n")
output.csv:
KeyA,1,KeyA,2,KeyA,3,KeyA,4,KeyA,5,KeyA,6,
KeyB,2,KeyB,3,KeyB,4,KeyB,5,KeyB,6,KeyB,7,
Upvotes: 1