2

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?

1
  • 1
    Do you want KeyA[ItemA] to be one row above KeyB[ItemR] in the CSV, or do you only want to print the csv row for KeyA? Would be cool if you could make the desired output a bit more clear :) Commented Dec 4, 2021 at 7:23

1 Answer 1

1

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,
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.