0

I have a dictionary that stores a list of items for each key as shown:

name_dict = {'MiddleName': ['H.', 'T.'], 'LastName': ['Perkins', 'Joseph'], 'FirstName': ['Elizabeth ', 'Scott ']}

I want to print the data in the dictionary as table format:

FirstName,MiddleName,LastName # the keys of the dictionary
Elizabeth,H.,Perkins #the values of the keys in one line (the first item in the list)
Scott,T.,Joseph #the values of the keys in new line (the following item in the list)

How to solve this problem?

I have tried doing the suggested solution by Gareth Latty, but that did not work.

with open('C:/Output.csv',"w+") as file:
    w = csv.DictWriter(file,name_dict.keys())
    w.writeheader()
    w.writerow(name_dict) 

It outputs the following:

MiddleName,LastName,FirstName
"['H.', 'T.']","['Perkins', 'Joseph']","['Perkins', 'Joseph']"

Any idea how to output the values (the item in the list) of each of the keys in new row?

Community
  • 1
  • 1
MEhsan
  • 2,184
  • 9
  • 27
  • 41

5 Answers5

1

I think you misuse dict. When you have multiple values, you should use a list of dicts and not a dict which the values are lists. Instead of

Dict = {'MiddleName': ['H.', 'T.'], 'LastName': ['Perkins', 'Joseph'], 'FirstName': ['Elizabeth ', 'Scott ']}

You should do:

Dict = [{'FirstName': 'Elizabeth', 'MiddleName': 'H.', 'LastName': 'Perkins'}, {'FirstName': 'Joseph', 'MiddleName': 'T. ', 'LastName': 'Scott'}]

or in a more readable version:

Dict = [
    {'FirstName': 'Elizabeth',   'MiddleName': 'H.',    'LastName': 'Perkins'},
    {'FirstName': 'Joseph',      'MiddleName': 'T. ',   'LastName': 'Scott'  }
]

If you want to print one line (one dictionary of the list), you can do something like that:

def printDict(d):
    print d["FirstName"] + "," + d["MiddleName"] + "," + d["LastName"]

And if you want to print each of the elements in the list you have:

def printList(l):
    for i in l:
        printDict(i)

And just use it like that:

printList(Dict)

With your first (original) Dict, accessing Dict["FirstName"] would return a list, and when printed it would print as:

["Elizabeth", "Joesph"]

But with the second (new way I suggested) Dict, accessing Dict[0]["FirstName"] would return a string, and will print like:

Elizabeth

Yotam Salmon
  • 2,400
  • 22
  • 36
  • I'd assume the dictionary in question isn't just hard coded into the actual code, this is not a "mususe of `dict`" but just not the right format for use with `csv.DictWriter` – Tadhg McDonald-Jensen Jun 17 '16 at 16:56
1

csv.DictWriter expects a dictionary with the field:single_line pairs for each row which is unfortunately not what you have, you basically need to convert your data structure to be a list of dicts for the single lines:

[{'MiddleName': 'H.', 'FirstName': 'Elizabeth ', 'LastName': 'Perkins'}, {'MiddleName': 'T.', 'FirstName': 'Scott ', 'LastName': 'Joseph'}]

You can convert it with something like this:

import csv

def seperate_entries(dict_of_lists):    
    iters = [(k,iter(v)) for k,v in dict_of_lists.items()]
    try:
        while True:
            yield {k:next(v) for k,v in iters}
    except StopIteration:
        return
name_dict = {'MiddleName': ['H.', 'T.'], 'LastName': ['Perkins', 'Joseph'], 'FirstName': ['Elizabeth ', 'Scott ']}

with open('sample.csv',"w+") as file:
    w = csv.DictWriter(file,name_dict.keys())
    w.writeheader()
    w.writerows(seperate_entries(name_dict))
Tadhg McDonald-Jensen
  • 20,699
  • 5
  • 35
  • 59
0

To access the keys in the Dictionary, you just need to do the following:

middleNames=Dict['Middlename'] 
firstNames=Dict['FirstName']
lastNames=Dict['LastName']

You now have access to the values stored in the inner list information, this can similarly be accessed by the following:

# Find how many items read (optional)
len(middleNames)

# Then iterate through the items
for mName in middleName:
   print mName   # this will print each list item e.g.

H.

T.

# for brevity, this is the same as doing this...
middleName[0] etc

Hope this helps.

rosera
  • 41
  • 4
0

I'm sure there are more efficient ways of achieving what you want but this lays down a simple outline of what you want and shows how you can achieve it.

names = {'MiddleName': ['H.', 'T.'], 'LastName': ['Perkins', 'Joseph'], 'FirstName': ['Elizabeth ', 'Scott ']}

output = open('output.txt','w')

#NOTE: this will write headers in alphabetical format. You will need to change that so it follows the FirstName, MiddleName, LastName pattern
for key in sorted(names.keys()):
    output.write(key + ',')

output.write('\n')

#assuming we always have same amount of middle, first, and last names
for i in range(len(names['FirstName'])): 

    personFname = ''
    personLname = ''
    personMname = ''

    for key in names.keys():
        if key == 'MiddleName':
            personMname = names[key][i]
        elif key == 'FirstName':
            personFname = names[key][i]
        elif key == 'LastName':
            personLname = names[key][i]

    output.write(personFname + ',' + personMname + ',' + personLname)
    output.write('\n')

output.close()
Ishaan
  • 707
  • 1
  • 7
  • 16
0

You need define how many row you have. Just flat it into rows with all keys in Dict.

import csv

Dict = {'MiddleName': ['H.', 'T.'], 'LastName': ['Perkins', 'Joseph'], 'FirstName': ['Elizabeth ', 'Scott ']}

len_row = 2
with open('Output.csv', "w+") as file:
    w = csv.DictWriter(file, Dict.keys())
    w.writeheader()
    for i in range(len_row):
        row = {}
        for k in Dict.keys():
            for v in Dict.values():
                row[k] = Dict[k][i]
        w.writerow(row)
giaosudau
  • 2,211
  • 6
  • 33
  • 64