[英]Values in List of Dicts - Python 3
我想提取一個字典值列表,以便可以將它們寫入csv。
我試圖使用上一個SO問題中的信息來復制所有鍵值。
In [41]: dicts = [
...: {"name": "Tom", "age": 10},
...: {"name": "Mark", "age": 5},
...: {"name": "Pam", "age": 7},
...: {"name": "Dick", "age": 12},
...: ]
但是我得到的輸出非常復雜,有時是字典,有時是值。
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: {...}}
我希望輸出中沒有字典,所有鍵和值都不會提取。 我看到有更好的方法可以做到這一點,但是錯誤是由於錯誤地粘貼到ipython中。
編輯的更新的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
為什么不只列舉列表並提取值:
for i, entry in enumerate(dicts):
... print entry['name']," ",entry['age']
然后可以將值寫入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']])
您可以重新構建字典以滿足您的需求:
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))
但是,要將它們直接寫入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)
您可以將相同鍵字典的列表轉換為具有相同鍵的字典,並且值是原始順序的原始值的列表:
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.