简体   繁体   中英

Is it possible to write a Dictionary of Dictionaries to a CSV file?

The dictionary format I'm referring to looks like this (FYI, these are just football players):

player_list = {
    'Shkodran Mustafi': {'first': 'Shkodran', 'last': 'Mustafi', 'team': 'Arsenal'},
    'Héctor Bellerín': {'first': 'Héctor', 'last': 'Bellerín', 'team': 'Arsenal'},
    'Sead Kolasinac': {'first': 'Sead', 'last': 'Kolasinac', 'team': 'Arsenal'}
    }

Is it possible to use this dictionary to write something like the table below to a CSV?

First Name:    Last Name:     Team: 

Shkodran       Mustafi        Arsenal
Héctor         Bellerín       Arsenal
Sead           Kolasinac      Arsenal

Any help on how to achieve this would be greatly appreciated! THANK YOU!

If you really want the columns from the inner dictionaries written to a CSV file, it can be done very easily with Pandas.

player_list = {
    'Shkodran Mustafi': {'first': 'Shkodran', 'last': 'Mustafi', 'team': 'Arsenal'},
    'Héctor Bellerín': {'first': 'Héctor', 'last': 'Bellerín', 'team': 'Arsenal'},
    'Sead Kolasinac': {'first': 'Sead', 'last': 'Kolasinac', 'team': 'Arsenal'},}
import pandas as pd
df = pd.DataFrame(player_list).T
df.columns = ['First Name', 'Last Name', 'Team']
df.to_csv('test.csv', index=False)

Will produce the CSV equivalent of the table that you posted in your question:

First Name,Last Name,Team
Shkodran,Mustafi,Arsenal
Héctor,Bellerín,Arsenal
Sead,Kolasinac,Arsenal

So basically iterating the dictionary and putting it in.csv format?

player_list = {
    'Shkodran Mustafi': {'first': 'Shkodran', 'last': 'Mustafi', 'team': 'Arsenal'},
    'Héctor Bellerín': {'first': 'Héctor', 'last': 'Bellerín', 'team': 'Arsenal'},
    'Sead Kolasinac': {'first': 'Sead', 'last': 'Kolasinac', 'team': 'Arsenal'}}

keys = ['first', 'last', 'team']

with open("data.csv", 'w') as wf:
    wf.write("First Name:,Last Name:,Team:\n")
    for k, v in player_list.items():
        to_write = []
        for key in keys:
             to_write.append(str(v[key]))
        wf.write(','.join(to_write) + '\n')

In this case, you don't even need to worry about the fact that it's a dictionary of dictionaries. You're only ever outputting the "inner" dictionary anyway, so you can do something like this:

player_list = {
'Shkodran Mustafi': {'first': 'Shkodran', 'last': 'Mustafi', 'team': 'Arsenal'},
'Héctor Bellerín': {'first': 'Héctor', 'last': 'Bellerín', 'team': 'Arsenal'},
'Sead Kolasinac': {'first': 'Sead', 'last': 'Kolasinac', 'team': 'Arsenal' }
}

with open('output.csv', 'w') as writer:
    writer.write("First Name:,Last Name:,Team:\n")
    for key, value in player_list.items():
        writer.write(value['first'] + ',' + value['last'] + ',' + value['team'] + '\n')

In this case, there are only 3 values, so I just used string concatenation, but if you're doing more values, you may want to try something like what @tgikal is doing.

CSV is a format which can represent any hash of hashes or if I guess correctly that you are using Python dictionary of dictionaries.

You need to write the correct parser

One way would be to use a different different delimiter to represent nested hashes eg brackets {

{,Shkodran Mustafi,{,first,Shkodran,last,Mustafi,team,Arsenal,},}

I suggest you use json, yaml or hocon they are easier on the human eye

An object you may find useful is csv.DictWriter : https://docs.python.org/2/library/csv.html#csv.DictWriter

example usage:

import csv

player_list = {
    'Shkodran Mustafi': {'first': 'Shkodran', 'last': 'Mustafi','team': 'Arsenal'},
    'Héctor Bellerín': {'first': 'Héctor', 'last': 'Bellerín','team': 'Arsenal'},
    'Sead Kolasinac': {'first': 'Sead', 'last': 'Kolasinac', 'team': 'Arsenal'}
}

with open("player_data.csv", 'w') as fp:
    writer = csv.DictWriter(fp, fieldnames=['first', 'last', 'team'])
    writer.writeheader()
    for player_name, player_info in player_list.items():
        writer.writerow(player_info)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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