【问题标题】:Table/Data manipulation with Python Dictionary使用 Python Dictionary 进行表/数据操作
【发布时间】:2014-07-20 15:15:58
【问题描述】:

我需要帮助来完成这个 python 脚本。我是一家公司的实习生,这是我的第一周。我被要求开发一个 python 脚本,它将采用 .csv 并将任何相关列放入(附加)到一列中,以便它们只有 15 个左右的必要列,其中包含数据。例如,如果有 zip4、zip5 或邮政编码列,他们希望这些都位于邮政编码列的下方。

我这周刚开始学习 python,因为我正在做这个项目,所以请原谅我的菜鸟问题和词汇。我不是在找你们为我做这件事。我只是在寻找一些指导。事实上,我想了解更多关于python的信息,所以任何可以引导我走向正确方向的人,请帮助。

我正在使用字典键和值。键是第一行中的每一列。每个键的值是剩余的行(第二到 3000 行)。现在,我只得到一个键:值对。我只得到最后一行作为我的值数组,而且我只得到一个键。另外,我收到一条 KeyError 消息,所以我的密钥没有被正确识别。到目前为止,我的代码在下面。我会继续努力,非常感谢任何帮助!希望我可以通过帮我喝啤酒的人,我可以稍微了解一下他们的大脑:)

感谢您的宝贵时间

# To be able to read csv formated files, we will frist have to import the csv module
import csv

# cols = line.split(',')# each column is split by a comma
#read the file
CSVreader = csv.reader(open('N:/Individual Files/Jerry/2013 customer list qc, cr, db, gb 9-19-2013_JerrysMessingWithVersion.csv', 'rb'), delimiter=',', quotechar='"')

# define open dictionary
SLSDictionary={}# no empty dictionary. Need column names to compare to. 


i=0
#top row are your keys. All other rows are your values

#adjust loop
for row in CSVreader:
# mulitple loops needed here
    if i == 0:
            key = row[i]
    else:
            [values] = [row[1:]]
            SLSDictionary = dict({key: [values]}) # Dictionary is keys and array of values
    i=i+1


#print Dictionary to check errors and make sure dictionary is filled with keys and values        
print SLSDictionary

# SLSDictionary has key of zip/phone plus any characters
#SLSDictionary.has_key('zip.+')
SLSDictionary.has_key('phone.+')

#value of key are set equal to x. Values of that column set equal to x
#[x]=value

#IF SLSDictionary has the key of zip plus any characters, move values to zip key
#if true:   
#        SLSDictionary['zip'].append([x])
    #SLSDictionary['phone_home'].append([value]) # I need to append the values of the specific column, not all columns
    #move key's values  to correct, corresponding key
SLSDictionary['phone_home'].append(SLSDictionary[has_key('phone.+')])#Append the values of the key/column 'phone plus characters' to phone_home key/column in SLSDictionary
#if false:
#        print ''
    # go to next key

SLSDictionary.has_value('')

if true:
    print 'Error: No data in column'

# if there's no data in rows 1-?. Delete column
#if value <= 0:
#        del column

print SLSDictionary 

【问题讨论】:

  • 您不只是使用 csv.DictReader 有什么原因吗?
  • 我应该使用 csv.DictReader 而不是 csv.reader?

标签: python csv dictionary key


【解决方案1】:

快速查看发现了几个错误。您需要注意的一件事是,您每次都在为现有字典分配一个新值:

SLSDictionary = dict({key: [values]})

每次 SLSDictionary 进入该循环时,您都会为其重新分配一个新值。因此,最后你只有最底部的条目。要向字典添加键,请执行以下操作:

SLSDictionary[key] = values

另外你不应该在这一行中需要括号:

[values] = [row[1:]]

应该只是:

values = row[1:]

但最重要的是,您将永远只有一个键,因为您会不断增加 i 值。所以它永远只有一个键,所有的东西都会不断地分配给它。如果没有 CSV 外观的示例,我无法指导您如何重组循环以使其捕获所有键。

假设您的 CSV 如您所描述的那样:

Col1, Col2, Col3, Col4
Val1, Val2, Val3, Val4
Val11, Val22, Val33, Val44
Val111, Val222, Val333, Val444

那么你可能想要这样的东西:

dummy = [["col1", "col2", "col3", "col4"],
         ["val1", "val2", "val3", "val4"],
         ["val11", "val22", "val33", "val44"],
         ["val111", "val222", "val333", "val444"]]

column_index = []
SLSDictionary = {}

for each in dummy[0]:
    column_index.append(each)
    SLSDictionary[each] = []

for each in dummy[1:]:
    for i, every in enumerate(each):
        try:
            if column_index[i] in SLSDictionary.keys():
                SLSDictionary[column_index[i]].append(every)
        except:
            pass

print SLSDictionary

哪个产量...

{'col4': ['val4', 'val44', 'val444'], 'col2': ['val2', 'val22', 'val222'], 'col3': ['val3', 'val33', 'val333'], 'col1': ['val1', 'val11', 'val111']}

如果您希望它们保持有序,请将字典类型更改为 OrderedDict()

【讨论】:

  • 非常感谢您提供的信息!你是一个救生员。我想知道我做了什么错误让我只得到了 for 循环中的最后一个结果。有没有办法将整个 CSV 导入虚拟字段?
  • 我正在尝试编译代码并测试它是否有效,但我家用笔记本电脑上的文本编辑器不如我工作桌面上的文本编辑器,所以一旦我'能够测试脚本,我会让你知道它是如何工作的。再次感谢您的所有建议!
  • CSVreader 应该基本上给您与虚拟字段相同的结果。我只是以它为例。
猜你喜欢
  • 1970-01-01
  • 2017-12-18
  • 1970-01-01
  • 1970-01-01
  • 2012-08-26
  • 1970-01-01
  • 2018-07-11
  • 1970-01-01
  • 2022-07-02
相关资源
最近更新 更多