简体   繁体   English

将CSV转换为具有多个值的字典?

[英]Convert a csv to a dictionary with multiple values?

I have a csv file like this: 我有这样的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

I want to convert it to a dictionary like the following: 我想将其转换为如下字典:

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

And then, fill the missing numbers in the range in the values: 然后,在值的范围内填写缺失的数字:

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

Right now i have tried to build the dictionary using solution suggested here , but it overwrites the old value with new one. 现在,我已尝试使用此处建议的解决方案来构建字典,但是它将新值覆盖旧值。

Any help would be great. 任何帮助都会很棒。

Here is a function that i wrote for converting csv2dict 这是我编写的用于转换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   

Easiest is to use collections.defaultdict() with a list: 最简单的方法是将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)

This also expands the ranges on the fly as you read the data. 当您读取数据时,这也可以实时扩展范围。

Based on what you have tried - 根据您的尝试-

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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