this question has answer here:
- write values of python dictionary file 2 answers
i have list of dictionaries such as:
values = [{'name': 'john doe', 'age': 26, 'id': '1279abc'}, {'name': 'jane smith', 'age': 35, 'id': 'bca9721'} ]
what i'd print list of dictionaries tab delimited text file this:
name age id john doe 26 1279abc jane smith 35 bca9721
however, unable wrap head around printing values, of right i'm printing entire dictionary per row via:
for in values: f.write(str(i)) f.write("\n")
perhaps need iterate through each dictionary now? i've seen people use like:
for i, n in iterable: pass
but i've never understood this. able shed light this?
edit:
appears use this, unless has more pythonic way (perhaps can explain "for i, n in interable"?):
for dic in values: entry in dic: f.write(dic[entry])
this simple enough accomplish dictwriter
. purpose write column-separated data, if specify our delimiter of tabs instead of commas, can make work fine.
from csv import dictwriter values = [{'name': 'john doe', 'age': 26, 'id': '1279abc'}, {'name': 'jane smith', 'age': 35, 'id': 'bca9721'}] keys = values[0].keys() open("new-file.tsv", "w") f: dict_writer = dictwriter(f, keys, delimiter="\t") dict_writer.writeheader() value in values: dict_writer.writerow(value)