I'm trying to create a csv file from a list of dictionary items where each dictionary in the list has the same keys. I want the csv file to have the keys in the first column and the remaining columns will have the values for each dictionary in the list corresponding to the key.

My desired output is:item1,3,2,18
item2,3,6,12
item3,5,3,1


The following code works but it seems there should be a more elegant way to do this.

l = [
    {'item1':3, 'item2':3, 'item3':5},
    {'item1':2, 'item2':6, 'item3':3},
    {'item1':18, 'item2':12, 'item3':1} ]

str_list = []
for d in l:
    str_list.append(str(d['item1']))
str_list.insert(0,'item1')
out = ','.join(str_list)
print(out)
str_list = []
for d in l:
    str_list.append(str(d['item2']))
str_list.insert(0,'item2')
out = ','.join(str_list)
print(out)
str_list = []
for d in l:
    str_list.append(str(d['item3']))
str_list.insert(0,'item3')
out = ','.join(str_list)
print(out)

Do it in one pass by converting to a dictionary of lists which can then be copied to the file.

test_list = [
    {'item1':3, 'item2':3, 'item3':5},
    {'item1':2, 'item2':6, 'item3':3},
    {'item1':18, 'item2':12, 'item3':1} ]

redone_dict = {}
for dic in test_list:
    for key in dic:
        if key not in redone_dict:
            redone_dict[key] = []
        redone_dict[key].append(dic[key])
print redone_dict

Thanks. Much nicer. Now I just need to figure out how to print/write in the order I want. I'll try to figure that out on my own.

After working on this some more I've realized I should probably put in the format {'key1':

  • , 'key2':
  • } to begin with, then I won't have to do the conversion.
  • I'll have to re-write my other code to format differently. I suppose I'll take a look at which way runs faster.
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.