007mrviper
007mrviper

Reputation: 519

How to create comma-separated values from nested dictionary?

I need to create a CSV file filled with data from a nested dictionary.

I am referring to this question: Convert Nested Dictionary to CSV Table.

I checked this problem: From Nested Dictionary to CSV File, and found a way to create comma-separated values.

My nested dictionary looks like this:

users_item = {
    "Angelica": {
    "Blues Traveler": 3.5,
    "Broken Bells": 2.0,
    "Norah Jones": 4.5,
    "Phoenix": 5.0,
    "Slightly Stoopid": 1.5,
    "The Strokes": 2.5,
    "Vampire Weekend": 2.0
},
"Bill":{
    "Blues Traveler": 2.0,
    "Broken Bells": 3.5,
    "Deadmau5": 4.0,
    "Phoenix": 2.0,
    "Slightly Stoopid": 3.5,
    "Vampire Weekend": 3.0}
}

with open('output1.csv', 'w') as csv_file:
    csvwriter = csv.writer(csv_file, delimiter=',')
    for session in users_item:
        for item in users_item[session]:
            csvwriter.writerow([session, item, users_item[session][item]])

I generated this output.

Angelica,Blues Traveler,3.5
Angelica,Broken Bells,2.0
Angelica,Norah Jones,4.5
Angelica,Phoenix,5.0
Angelica,Slightly Stoopid,1.5
Angelica,The Strokes,2.5
Angelica,Vampire Weekend,2.0
Bill,Blues Traveler,2.0
Bill,Broken Bells,3.5
Bill,Deadmau5,4.0
Bill,Phoenix,2.0
Bill,Slightly Stoopid,3.5
Bill,Vampire Weekend,3.0

However, I need to generate the output in the following format:

Angelica,Blues Traveler,3.5,Broken Bells,2.0,Norah Jones,4.5,Phoenix,5.0,Slightly Stoopid,1.5,The Strokes,2.5,Vampire Weekend,2.0
Bill,Blues Traveler,2.0,Broken Bells,3.5,Deadmau5,4.0,Phoenix,2.0,Slightly Stoopid,3.5,Vampire Weekend,3.0

Could you please tell me how to modify the code to obtain the output that I showed above?

Upvotes: 2

Views: 415

Answers (1)

RoadRunner
RoadRunner

Reputation: 26315

Your quite close. I would just modify your approach flatten the inner dict items into a list using itertools.chain.from_iterable, then combine it with the user's name and write the list to the CSV file.

Modified code:

from csv import writer
from itertools import chain

users_item = {
    "Angelica": {
        "Blues Traveler": 3.5,
        "Broken Bells": 2.0,
        "Norah Jones": 4.5,
        "Phoenix": 5.0,
        "Slightly Stoopid": 1.5,
        "The Strokes": 2.5,
        "Vampire Weekend": 2.0,
    },
    "Bill": {
        "Blues Traveler": 2.0,
        "Broken Bells": 3.5,
        "Deadmau5": 4.0,
        "Phoenix": 2.0,
        "Slightly Stoopid": 3.5,
        "Vampire Weekend": 3.0,
    },
}  

with open("output.csv", mode="w", newline='') as f:
    writer = writer(f)
    for user, items in users_item.items():
        flattened_items = list(chain.from_iterable(items.items()))
        writer.writerow([user, *flattened_items])

Or flattening using a list comprehension:

with open("output.csv", mode="w", newline="") as f:
    writer = writer(f)
    for user, items in users_item.items():
        row = [item for kvp in items.items() for item in kvp]
        writer.writerow([user, *row])

Or a simpler approach with just extending the key value pairs into a list one at a time:

with open("output.csv", mode="w", newline="") as f:
    writer = writer(f)
    for user, items in users_item.items():
        row = [user]
        for k, v in items.items():
            row.extend([k, v])
        writer.writerow(row)

output.csv

Angelica,Blues Traveler,3.5,Broken Bells,2.0,Norah Jones,4.5,Phoenix,5.0,Slightly Stoopid,1.5,The Strokes,2.5,Vampire Weekend,2.0
Bill,Blues Traveler,2.0,Broken Bells,3.5,Deadmau5,4.0,Phoenix,2.0,Slightly Stoopid,3.5,Vampire Weekend,3.0

Upvotes: 2

Related Questions