Write List Of Dictionary Values To File
I have a list of dictionaries such as: values = [{'Name': 'John Doe', 'Age': 26, 'ID': '1279abc'}, {'Name': 'Jane Smith', 'Age': 35, 'ID': 'bca9721'} ] What I'd
Solution 1:
This is simple enough to accomplish with a DictWriter
. Its purpose is to write column-separated data, but if we specify our delimiter to be that of tabs instead of commas, we can make this work just fine.
from csv import DictWriter
values = [{'Name': 'John Doe', 'Age': 26, 'ID': '1279abc'},
{'Name': 'Jane Smith', 'Age': 35, 'ID': 'bca9721'}]
keys = values[0].keys()
with open("new-file.tsv", "w") as f:
dict_writer = DictWriter(f, keys, delimiter="\t")
dict_writer.writeheader()
for value in values:
dict_writer.writerow(value)
Solution 2:
f.write('Name\tAge\tID')
forvaluein values:
f.write('\t'.join([value.get('Name'), str(value.get('Age')), value.get('ID')]))
Solution 3:
You're probably thinking of the items() method. This will return the key and value for each entry in the dictionary. http://www.tutorialspoint.com/python/dictionary_items.htm
for k,v in values.items():
pass
Solution 4:
# assuming your dictionary is in valuesimport csv
withopen('out.txt', 'w') as fout:
writer = csv.DictWriter(fout, fields=values.keys(). delimiter="\t")
writer.writeheader()
writer.writerow(values.values())
Post a Comment for "Write List Of Dictionary Values To File"