简体   繁体   English

如何从嵌套字典创建逗号分隔值?

[英]How to create comma-separated values from nested dictionary?

I need to create a CSV file filled with data from a nested dictionary.我需要创建一个 CSV 文件,其中填充了来自嵌套字典的数据。

I am referring to this question: Convert Nested Dictionary to CSV Table .我指的是这个问题: 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.我检查了这个问题: 从嵌套字典到 CSV 文件,并找到了一种创建逗号分隔值的方法。

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.我生成了这个 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:但是,我需要按以下格式生成 output:

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?你能告诉我如何修改代码以获得我上面显示的 output 吗?

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.我将修改您的方法,使用itertools.chain.from_iterable将内部 dict 项展平为列表,然后将其与用户名结合起来,并将列表写入 CSV 文件。

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 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM