【问题标题】:List to Dictionary - multiple values to key列表到字典 - 要键的多个值
【发布时间】:2016-07-17 08:03:12
【问题描述】:

我对以下编码和寻求指导非常陌生...

我目前有一个这样的 csv 输出:

'Age, First Name, Last Name, Mark'  
'21, John, Smith, 68'  
'16, Alex, Jones, 52'  
'42, Michael, Carpenter, 92 '

如何创建一个最终看起来像这样的字典:

dictionary = {('age' : 'First Name', 'Mark'), ('21' : 'John', '68'), etc}

我希望第一个值成为键 - 并且只需要另外两个值,但我很难找到解决方法。

到现在为止

data = open('test.csv', 'r').read().split('\n')

我尝试将每个部分拆分成一个字符串

for row in data:  
     x = row.split(',')

编辑:

感谢那些为解决我的问题提供意见的人。

所以使用后

myDic = {}
for row in data:
    tmpLst = row.split(",")
    key = tmpLst[0]
    value = (tmpLst[1], tmpLst[-1])
    myDic[key] = value

我的数据出来了

['Age', 'First Name', 'Last Name', 'Mark']
['21', 'John', 'Smith', '68']
['16', 'Alex', 'Jones', '52']
['42', 'Michael', 'Carpenter', '92']

但是得到一个 IndexError: list index out of range at the line

value = (tmpLst[1], tmpLst[-1])

尽管我可以看到它应该在索引的范围内。

有谁知道为什么会出现此错误或需要更改什么?

【问题讨论】:

  • 文件实际上是这样的吗?那不是 CSV……我不会在 CSV 文件中出现单引号和方括号。

标签: python-2.7 csv dictionary


【解决方案1】:

假设一个实际有效的 CSV 文件如下所示:

Age,First Name,Last Name,Mark
21,John,Smith,68
16,Alex,Jones,52
42,Michael,Carpenter,92

下面的代码应该做你想做的事:

from __future__ import print_function
import csv

with open('test.csv') as csv_file:
    reader = csv.reader(csv_file)

    d = { row[0]: (row[1], row[3]) for row in reader }

print(d)

# Output:
# {'Age': ('First Name', 'Mark'), '16': ('Alex', '52'), '21': ('John', '68'), '42': ('Michael', '92')}

如果 d = { row[0]: (row[1], row[3]) for row in reader } 令人困惑,请考虑以下替代方案:

d = {}
for row in reader:
    d[row[0]] = (row[1], row[3])

【讨论】:

    【解决方案2】:

    我猜你想要这样的输出:

    dictionary = {'age' : ('First Name', 'Mark')} 然后就可以使用下面的代码了:

    myDic = {}
    for row in data:
        tmpLst = row.split(",")
        key = tmpLst[0]
        value = (tmpLst[1], tmpLst[-1])
        myDic[key] = value
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      • 2021-11-17
      • 2021-11-13
      相关资源
      最近更新 更多