[英]Values in List of Dicts - Python 3
I want to extract a list of dictionary values so I can write them to csv. 我想提取一个字典值列表,以便可以将它们写入csv。
Using the info in this previous SO question I am attempting to replicate for all key, values. 我试图使用上一个SO问题中的信息来复制所有键值。
In [41]: dicts = [
...: {"name": "Tom", "age": 10},
...: {"name": "Mark", "age": 5},
...: {"name": "Pam", "age": 7},
...: {"name": "Dick", "age": 12},
...: ]
However the output I am getting is very mixed, sometimes its a dict and sometimes a value. 但是我得到的输出非常复杂,有时是字典,有时是值。
In [25]: for item in dicts:
...: for k, v in item.items():
...: print("Key: {0} and Value: {1}".format(k,v))
...:
...:
Key: name and Value: {'name': 'Dick', 'age': 12, 0: {...}}
Key: age and Value: 10
Key: 0 and Value: {'name': 'Dick', 'age': 12, 0: {...}}
Key: name and Value: Mark
Key: age and Value: 5
Key: name and Value: Pam
Key: age and Value: 7
Key: name and Value: Dick
Key: age and Value: 12
Key: 0 and Value: {'name': 'Dick', 'age': 12, 0: {...}}
I want the output to have no dicts in it all keys and values extracted. 我希望输出中没有字典,所有键和值都不会提取。 There are better ways to do this I see but error was from pasting into ipython incorrectly. 我看到有更好的方法可以做到这一点,但是错误是由于错误地粘贴到ipython中。
Edited Updated Dicts Updated Output with updated Dicts does work as expected. 编辑的更新的Dicts和更新的Dicts的更新输出确实按预期方式工作。
In [49]: for item in dicts:
...: for k, v in item.items():
...: print("Key: {0} and Value: {1}".format(k,v))
...:
Key: name and Value: Tom
Key: age and Value: 10
Key: name and Value: Mark
Key: age and Value: 5
Key: name and Value: Pam
Key: age and Value: 7
Key: name and Value: Dick
Key: age and Value: 12
Why not just enumerate on the list and extract the values: 为什么不只列举列表并提取值:
for i, entry in enumerate(dicts):
... print entry['name']," ",entry['age']
And then the values can be written to the csv file 然后可以将值写入csv文件
with open('dict.csv', 'wb') as csv_file:
... writer = csv.writer(csv_file)
... for i, entry in enumerate(dicts):
... writer.writerow([entry['name'],entry['age']])
You can re-construct the dict to meet your needs: 您可以重新构建字典以满足您的需求:
dicts = [{'key': k, 'value': v} for item in dicts for k,v in item.items()]
for item in dicts:
print("Key: {key} and Value: {value}".format(**item))
But, to write them directly to csv, there is a better way: 但是,要将它们直接写入csv,有一种更好的方法:
import csv
dicts = [{'key': k, 'value': v} for item in dicts for k,v in item.items()]
with open('dicts.csv', 'wb') as f:
dict_writer = csv.DictWriter(f, dicts[0].keys())
dict_writer.writeheader()
dict_writer.writerows(dicts)
You can convert a list of same-keys dicts into a dict with the same keys and values are lists of the original values in original order: 您可以将相同键字典的列表转换为具有相同键的字典,并且值是原始顺序的原始值的列表:
dicts = [
{"name": "Tom", "age": 10},
{"name": "Pam", "age": 7},
{"name": "Dick", "age": 12},
]
dictoflists = {k: [d[k] for d in dicts] for k in dicts[0].keys()}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.