【问题标题】:CSV to Nested Python DictCSV 到嵌套 Python 字典
【发布时间】:2017-12-30 12:24:56
【问题描述】:

我想将此 csv 中的某些列导入嵌套的 python dict:

Name, Type, ID, Job, Height
Adam, Man, asmith, factory, 5
Ben, Man, bjones, mine, 6
Jamie, Woman, jbarnes, bank, 5.5

输出:

dict1 = { asmith: {Name:Adam, Type:Man, Height:5},
          bjones, {Name:Ben, Type:Man, Height:6},
          jbarnes:, {Name:Jamie,Type:Woman, Height:5.5} }

【问题讨论】:

  • 忘了提:标题在第 2 行 & 是否有特定的方式来选择要使用的列(有时我想排除列 - 这个前我想排除工作)

标签: python-2.7 csv dictionary nested


【解决方案1】:

我们可以使用csv中的DictReader来实现这一点:

from csv import DictReader

with open('data.csv') as csvfile:
    reader = DictReader(csvfile)
    result = {row[' ID'] : row for row in reader}

现在result 将是一个将IDs 映射到字典的字典。字典也将包含'ID'。现在result 将是:

{' bjones': {'Name': 'Ben', ' Type': ' Man', ' Height': ' 6', ' ID': ' bjones', ' Job': ' mine'}, ' jbarnes': {'Name': 'Jamie', ' Type': ' Woman', ' Height': ' 5.5', ' ID': ' jbarnes', ' Job': ' bank'}, ' asmith': {'Name': 'Adam', ' Type': ' Man', ' Height': ' 5', ' ID': ' asmith', ' Job': ' factory'}}

我们可以看到这些值没有被删除:它们在左侧和右侧包含空格。我们可以这样处理:

from csv import DictReader

with open('data.csv') as csvfile:
    reader = DictReader(csvfile)
    result = {}
    for row in reader:
        row = {k.strip():v.strip() for k,v in row.items()}
        result[row.pop('ID')] = row

这也会从字典中删除ID 键。现在的答案是:

>>> result
{'jbarnes': {'Name': 'Jamie', 'Height': '5.5', 'Job': 'bank', 'Type': 'Woman'}, 'bjones': {'Name': 'Ben', 'Height': '6', 'Job': 'mine', 'Type': 'Man'}, 'asmith': {'Name': 'Adam', 'Height': '5', 'Job': 'factory', 'Type': 'Man'}}

编辑:如果你想忽略第一行,你可以先在文件处理程序上调用next(..)

from csv import DictReader

with open('data.csv') as csvfile:
    next(csvfile)
    reader = DictReader(csvfile)
    result = {}
    for row in reader:
        row = {k.strip():v.strip() for k,v in row.items()}
        result[row.pop('ID')] = row

【讨论】:

  • 我建议使用row.pop('ID') 将其从字典中删除。
猜你喜欢
  • 1970-01-01
  • 2022-11-25
  • 2021-06-21
  • 1970-01-01
  • 2022-06-11
  • 2015-06-06
  • 2014-09-20
  • 1970-01-01
  • 2018-05-31
相关资源
最近更新 更多