Dicts列表中的值 - Python 3

时间:2017-08-30 22:31:42

标签: python list dictionary

我想提取字典值列表,以便将它们写入csv。

使用上一个SO question中的信息,我试图复制所有键值。

In [41]: dicts = [
    ...: {"name": "Tom", "age": 10},
    ...: {"name": "Mark", "age": 5},
    ...: {"name": "Pam", "age": 7},
    ...: {"name": "Dick", "age": 12},
    ...: ]

然而,我得到的输出非常复杂,有时是dict,有时是值。

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

3 个答案:

答案 0 :(得分:1)

为什么不在列表中枚举并提取值:

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']])

答案 1 :(得分:1)

您可以重新构建字典以满足您的需求:

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)

答案 2 :(得分:0)

您可以将相同键序列的列表转换为具有相同键的dict,值是原始顺序的原始值列表:

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()}