I have a few 'list' containing few dictionaries- say 3 dicts. 3 dictionaries as follows:
l开发者_如何学运维stone = [{'dc_test': 1}, {'ac_test':2}, {'con_test':3}]
lsttwo = [{'dc_test': 4}, {'ac_test':5}, {'con_test':6}]
How do i create new lists as follows:
newlistone = ['dc_test',1,4]
newlisttwo = ['ac_test',2,5]
newlistthree = ['con_test',3,6]
My objective is to write a new csv file, so that it shows as follows:
dc_test,1,4
ac_test,2,5
con_test,3,5
First convert your list to dictionaries
d = [dict(itertools.chain(*(d.iteritems() for d in a)))
for a in [lstone, lsttwo]]
Next build the transposed list:
keys = d[0].keys()
transposed = [[e[k] for k in keys] for e in d]
Finally, transpose and use csv.writer
to write this to a file:
with open("a.csv", "wb") as f:
csv.writer(f).writerows(zip(keys, *transposed))
Are you sure the input data can't be represented with 2-tuples instead of dicts?
If the answer is no, then other solutions I've seen so far won't work for all possible cases, like an input item having more than one entry in the dict. This one will:
from collections import defaultdict
lstone = [{'dc_test': 1}, {'ac_test':2}, {'con_test':3}]
lsttwo = [{'dc_test': 4}, {'ac_test':5}, {'con_test':6}]
# merge
merge = defaultdict(list)
for e in lstone + lsttwo:
for k, v in e.items():
merge[k].append(v)
# flatten
result = [ [k] + v for k, v in merge.items()]
print result
# your option as to how to convert to CSV
This is how you can create the lists:
def makeLists(*lists):
for dicts in zip(*lists):
key = dicts[0].iterkeys().next()
yield [key] + [d[key] for d in dicts]
newlistone, newlisttwo, newlistthree = makeLists(lstone, lsttwo)
This code assumes that each list contains the same number of dictionaries, and that corresponding dictionaries contain exactly on entry with the same key.
To write it all to a file use this:
with open("test.txt", "w") as file:
file.write(",".join(newlistone) + "\n")
# other lines individually
You can also put all lists in one list and loop over them when writing to the file.
精彩评论