【问题标题】:Convert a csv to a dictionary with multiple values?将 csv 转换为具有多个值的字典?
【发布时间】:2014-04-06 08:01:30
【问题描述】:

我有一个这样的 csv 文件:

pos,place
6696,266835
6698,266835
938,176299
940,176299
941,176299
947,176299
948,176299
949,176299
950,176299
951,176299
770,272944
2751,190650
2752,190650
2753,190650

我想把它转换成如下的字典:

{266835:[6696,6698],176299:[938,940,941,947,948,949,950,951],190650:[2751,2752,2753]}

然后,在值的范围内填充缺失的数字:

{{266835:[6696,6697,6698],176299:[938,939,940,941,942,943,944,945,946947,948,949,950,951],190650:[2751,2752,2753]}
}

现在我尝试使用建议的解决方案 here 构建字典,但它会用新值覆盖旧值。

任何帮助都会很棒。

这是我编写的用于转换 csv2dict 的函数

def csv2dict(filename):
"""
reads in a two column csv file, and the converts it into dictionary
"""
import csv
with open(filename) as f:
    f.readline()#ignore first line
    reader=csv.reader(f,delimiter=',')
    mydict=dict((rows[1],rows[0]) for rows in reader)
return mydict   

【问题讨论】:

  • csv.DictReader。我会举一个例子,但我自己从未使用过它,所以我也会仔细研究文档!这在算法上当然是可能的,但我认为csv.DictReader 会为你完成繁重的工作。
  • 我添加了一个我写的用于将 cdv 转换为字典的函数..
  • 第二组大括号是怎么回事,还是一个错误?至于值填写,您可以获得端点的最小值和最大值,并为每个端点生成一个范围(忽略间隙值)。
  • 第二组大括号被编辑添加...不知道为什么。

标签: python python-2.7 csv dictionary


【解决方案1】:

最简单的方法是将collections.defaultdict() 与列表一起使用:

import csv
from collections import defaultdict

data = defaultdict(list)

with open(inputfilename, 'rb') as infh:
    reader = csv.reader(infh)
    next(reader, None)  # skip the header

    for col1, col2 in reader:
        data[col2].append(int(col1))
        if len(data[col2]) > 1:
            data[col2] = range(min(data[col2]), max(data[col2]) + 1)

这也会在您读取数据时动态扩展范围。

【讨论】:

  • 在读取过程中将列表扩展到一个范围,而不是在读取每个键后运行一次,有什么优势?
  • @adsmith:确实没有多大优势,但它简化了这里的代码。
  • 谢谢。它起作用了,我确实必须更改最后一行才能将列表中的字符串转换为整数。 data[col2]=range(min(map(int,data[col2])),max(map(int,data[col2]))+1)
  • @msakya:啊,当然。我更改了另一行,将col1 改为整数。
  • @MartijnPieters 附注:是否可以仅扩展值中的选定范围。例如,如果值具有 [2,8,10,500,502],则仅将其扩展为 [2,3,4,5,6,7,8,9,10,501,502] 而不是 10 到 501 之间的所有数字。基本上使用阈值来展开。
【解决方案2】:

根据您的尝试 -

from collections import default dict

# open archive reader
myFile = open ("myfile.csv","rb")
archive = csv.reader(myFile, delimiter=',')
arch_dict = defaultdict(list)

for rows in archive: 
    arch_dict[row[1]].append(row[0])

print arch_dict 

【讨论】:

    猜你喜欢
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 2016-12-28
    • 1970-01-01
    • 2021-07-23
    • 2013-10-20
    • 2023-03-16
    相关资源
    最近更新 更多