繁体   English   中英

字典列表中的值-Python 3

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM