paris_serviola paris_serviola - 5 months ago 21
Python Question

Writing to CSV file from list of Dictionaries with each key having multiple values?

results = [
{"Name" : "Name1", "Issues" : ["issue1", "issue2", "issue3"]},
{"Name" : "Name2", "Issues" : "issue1"},
{"Name" : "Name3", "Issues" : ["issue2", "issue4"]},
{"Name" : "Name4", "Issues" : "issue4"}
]


Here is my example dictionary and Below is my code that I am using to write it to a CSV file.

writer = csv.DictWriter(filename, results[0].keys(), dialect ="excel", delimiter=',')
writer.writeheader()
for result in results:
writer.writerow(result)


This is the current output

Name,Issues
Name1,['issue1', 'issue2', 'issue3']
Name2,issue1
Name3,['issue2', 'issue4']
Name4,issue4


As you see there are times when there are multiple issues per name. I want them to separate them by different delimiters. For example

Name,Issues
Name1,issue1 issue2 issue3
Name2,issue1
Name3,issue2 issue4
Name4,issue4


How do I achieve this? I wanted answer especially with dict writer module.

Answer

Here is one way:

for result in results:
    writer.writerow({k:' '.join(v) if isinstance(v, list) else v
                    for k,v in result.items()})

.writerow() expects a dictionary, the keys and values of which are strings. Since your dictionary's values are sometimes lists, we need a bit of code to convert a list to a string.

Here is an explanation of the techniques I used:

' '.join(v)   # Converts the list (v) to a space-separated string

isinstance(v, list) # Decides if (v) is a list or not

' '.join(v) if isinstance(v, list) else v 
              # Evaluates to either v (if v is a string) 
              # or a string (if v is a list)

{k:...for k,v in result.items()} # Creates the new dictionary, where
                                 # all values are strings
Comments