代码之家  ›  专栏  ›  技术社区  ›  Logic9

.csv数据到Python中的字典中:重复值

  •  0
  • Logic9  · 技术社区  · 11 年前

    我试图将.csv数据转换为Python中的字典,但我似乎得到了重复的字典条目。

    这是.csv数据的示例:

    ticker,1,2,3,4,5,6
    XOM,10,15,17,11,13,20
    AAPL,12,11,12,13,11,22
    

    我的意图是使用第一列作为键,其余列作为值。理想情况下,我应该有3个条目:ticker、XOM和AAPL。但我得到的却是:

    {'ticker': ['1', '2', '3', '4', '5', '6']}
    {'ticker': ['1', '2', '3', '4', '5', '6']}
    {'XOM': ['10', '15', '17', '11', '13', '20']}
    {'ticker': ['1', '2', '3', '4', '5', '6']}
    {'XOM': ['10', '15', '17', '11', '13', '20']}
    {'AAPL': ['12', '11', '12', '13', '11', '22']}
    

    所以看起来我得到了第1行,然后是第1&2,然后行1、2&3.

    这是我使用的代码:

    def data_pull():
        #gets data out of a .csv file
        datafile = open("C:\sample.csv")
        data = [] #blank list
        dict = {} #blank dictionary
        for row in datafile:
                data.append(row.strip().split(",")) #removes whitespace and commas
                for x in data: #organizes data from list into dictionary
                    k = x[0]
                    v = x[1:]
                    dict = {k:v for x in data}
                    print dict
    
    data_pull()
    

    我想弄清楚为什么会出现重复的条目。

    3 回复  |  直到 11 年前
        1
  •  2
  •   Martijn Pieters    11 年前

    你有太多的循环;你延伸 data 然后整个循环 数据 列出迄今为止收集的所有条目:

    for row in datafile:
        data.append(row.strip().split(",")) #removes whitespace and commas
        for x in data:
            # will loop over all entries parsed so far
    

    所以你可以在 数据 ,然后用一个项目循环列表:

    data = [['ticker', '1', '2', '3', '4', '5', '6']]
    

    然后你会读下一行并附加到 数据 ,然后你循环 数据 再次并处理:

    data = [
        ['ticker', '1', '2', '3', '4', '5', '6'],
        ['XOM', '10', '15', '17', '11', '13', '20'],
    ]
    

    所以迭代两次,然后添加下一行,循环三次,等等。

    您可以将其简化为:

    for row in datafile:
        x = row.strip().split(",")
        dict[x[0]] = x[1:]
    

    您可以使用 csv module :

    import csv
    
    def data_pull():
        results = {} 
    
        with open("C:\sample.csv", 'rb') as datafile:
            reader = csv.reader(datafile)
            for row in reader:
                results[row[0]] = row[1:]
    
        return results
    
        2
  •  0
  •   Ewan    11 年前

    使用内置的 csv 模块:

    import csv
    
    output = {}
    
    with open("C:\sample.csv") as f:
        freader = csv.reader(f)
        for row in freader:
            output[row[0]] = row[1:]
    
        3
  •  0
  •   Nigel Tufnel    11 年前

    循环 for x in data 应该在循环之外 for row in datafile :

    for row in datafile:
        data.append(row.strip().split(",")) #removes whitespace and commas
    for x in data: #organizes data from list into dictionary
        k = x[0]
    

    csv 模块可以是您的朋友:

    with open("text.csv") as lines:
        print {row[0]: row[1:] for row in csv.reader(lines)}
    

    旁注。使用Windows路径的原始字符串总是一个好主意:

    open(r"C:\sample.csv")
    

    如果您的文件名为, C:\text.csv 然后 \t 将被解释为 tab 性格