0

I have a list:

OrderedDict([('user', 'john'), ('password', '7f5a343ca80b8127abb97d5dc5459193'), ('firstname', 'John'), ('valid', 'VALID')])
OrderedDict([('user', 'leila'), ('password', 'c769c2bd15500dd906102d9be97fdceb'), ('firstname', 'Leila'), ('valid', 'VALID')])
OrderedDict([('user', 'chris'), ('password', '5badcaf789d3d1d09794d8f021f40f0e'), ('firstname', 'Christopher'), ('valid', 'VALID')])
OrderedDict([('user', 'phill'), ('password', '21b72c0b7adc5c7b4a50ffcb90d92dd6'), ('firstname', 'Phill'), ('valid', 'VALID')])
OrderedDict([('user', 'morton'), ('password', '5f4dcc3b5aa765d61d8327deb882cf99'), ('firstname', 'Morton'), ('valid', 'VALID')])

I want to put this into a .CSV - basically the file is to store users, and I have a program that adds users with passwords/hashes.

I currently have:

with open("output2.csv", 'w') as outputFile:
        wr = csv.writer(outputFile, dialect='excel')
        n = 0
        while n < len(dict_list):
            print(dict_list[n])
            wr.writerow(dict_list[n])
            n += 1
    quit()

But the .CSV file only shows this:

user,password,firstname,valid
user,password,firstname,valid
user,password,firstname,valid
user,password,firstname,valid
user,password,firstname,valid

I do need that as the first line of the CSV file but I need each entry to be printed without the heading underneath.

taras
  • 5,216
  • 9
  • 32
  • 41
user3103598
  • 185
  • 1
  • 10
  • Possible duplicate of [How do I convert this list of dictionaries to a csv file?](https://stackoverflow.com/questions/3086973/how-do-i-convert-this-list-of-dictionaries-to-a-csv-file) – RoadRunner Jul 24 '18 at 09:14

3 Answers3

3

You should use csv.DictWriter instead of csv.writer.
DictWriter's writerow accepts a dict, while writer.writerow
expects an iterable, so when you pass a dict instead it writes its keys rather then values.

Edit:

In order to write a header with your dict's keys you should add the following line before writing your rows:

wr.writeheader()

Besides, there exists writerows method which takes the whole list of dicts and writes it to the file.
So, to wrap up, your code should look like:

with open("output2.csv", 'w') as outputFile:
    wr = csv.DictWriter(outputFile, fieldnames=dict_list[0].keys(), dialect='excel')
    wr.writeheader()
    wr.writerows(dict_list)
taras
  • 5,216
  • 9
  • 32
  • 41
  • 1
    This will throw an error – DictWriter needs the argument fieldnames, such as: wr = csv.DictWriter(outputFile, fieldnames=['user', 'valid', 'firstname', 'password'], dialect='excel') – Michele Tonutti Jul 24 '18 at 09:36
  • @michetonu, thanks! I missed that `fieldnames` is not an optional argument. – taras Jul 24 '18 at 09:42
0

You should always use pandas for data manipulation. You can create a dataframe from a list of (ordered) dicts, and then use pandas' to_csv function to dump the whole thing to a file.

import pandas as pd
odList = [ordered_dict1, ordered_dict2, ordered_dict3, ordered_dict4, ordered_dict5]

output = pd.DataFrame(odList)

This will output:

     user                          password    firstname  valid
0    john  7f5a343ca80b8127abb97d5dc5459193         John  VALID
1   leila  c769c2bd15500dd906102d9be97fdceb        Leila  VALID
2   chris  5badcaf789d3d1d09794d8f021f40f0e  Christopher  VALID
3   phill  21b72c0b7adc5c7b4a50ffcb90d92dd6        Phill  VALID
4  morton  5f4dcc3b5aa765d61d8327deb882cf99       Morton  VALID

To save it to a csv file:

output_path = 'your_file_name.csv'
output.to_csv(output_path)

To exclude the index (the numbers on the left) from the csv, set index=False:

output.to_csv(output_path, index=False)
Michele Tonutti
  • 3,758
  • 17
  • 20
  • How is this irrelevant? it does exactly what OP wanted to do. – Michele Tonutti Jul 24 '18 at 09:28
  • It's irrelevant because you absolutely and definitely _dont_ need panda to solve the problem. Adding a dependancy on a huge lib to only use one single side-feature when the problem can be easily solved without by passing the dict's values instead of the dict itself (or by using a csv.DictWriter) goes against all good practices. – bruno desthuilliers Jul 24 '18 at 09:59
  • 2
    Apparently it does the job and is a great alternative for this task. Whether or not pandas introduces another major dependency for the OP is so far unknown, and none of our business. – mjoppich Jul 24 '18 at 10:30
  • Exactly, `csv` as a package is more than fine, but for any kind of manipulation or analysis on the fly `pandas` is vastly superior and flexible. OP should at the very least be aware of the option. I really do not understand this fiery reaction. – Michele Tonutti Jul 24 '18 at 12:21
  • 1
    @brunodesthuilliers no one is saying this is the best answer. You are right, you *don't* need pandas to solve the problem, and *that* is irrelevant. That is never what submitting an answer is about, or SO would only allow ONE answer per question. Downvoting this is insane, it's a perfectly good solution. Pandas is a very popular lib, and a lot of people already have it. And if they don't, they can get it, and if not, see another answer. +1. Saying "always" to use pandas is a bit strong, though. – Matt Messersmith Jul 28 '18 at 19:11
-1

Because

dict_list[n]

is one of your OrderedDicts .

Then

wr.writerow(dict_list[n])

would iterate over your ordered dictionary.

However that will be a list of the keys.

What you possibly rather want:

wr.writerow([dict_list[n][x] for x in dict_list[n]])

Which takes the value for each key in your dictionary.

mjoppich
  • 2,279
  • 1
  • 8
  • 13