使用值和预定义键更新字典

时间:2018-07-31 19:09:40

标签: python python-2.7 dictionary updates xlrd

我想创建一个具有预定义键的字典,如下所示:

dict = {'state':'', 'county': ''}

并通读并从电子表格中获取值,如下所示:

for row in range(rowNum):
    for col in range(colNum):

并更新键'state'(sheet.cell_value(row, 1))和'county'(sheet.cell_value(row, 1))的值,如下所示:

dict[{}]

我对如何通过状态键获取状态值和如何通过县键获取县值感到困惑。有什么建议吗?

所需结果如下:

>>>print dict
[
 {'state':'NC', 'county': 'Nash County'}, 
 {'state':'VA', 'county': 'Albemarle County'}, 
 {'state':'GA', 'county': 'Cook County'},....
]

2 个答案:

答案 0 :(得分:1)

我对您的问题做了一些假设。您在评论中提到州在索引1上,县在索引3上;索引2是什么?我以为它们是顺序发生的。除此之外,还需要一种可以将标题映射到数据列的方法,因此我使用了列表来保持标题的顺序。

# A list containing the headings that you are interested in the order in which you expect them in your spreadsheet
list_of_headings = ['state', 'county']
# Simulating your spreadsheet
spreadsheet = [['NC', 'Nash County'], ['VA', 'Albemarle County'], ['GA', 'Cook County']]
list_of_dictionaries = []

for i in range(len(spreadsheet)):
    dictionary = {}
    for j in range(len(spreadsheet[i])):
        dictionary[list_of_headings[j]] = spreadsheet[i][j]
    list_of_dictionaries.append(dictionary)

print(list_of_dictionaries)

答案 1 :(得分:0)

Raqib的答案部分正确,但必须进行修改才能与具有行和列以及xlrd mod的实际电子表格一起使用。我要做的是首先使用xlrd方法来获取想要的单元格值并将其放入列表中(类似于上面显示的spreadsheet变量raqib)。并非参数sIcI是我在上一步中选择的列索引值。 sI=StateIndexcI=CountyIndex

list =[]
for row in range(rowNum):
    for col in range(colNum):
        list.append([str(sheet.cell_value(row, sI)), str(sheet.cell_value(row, cI))])

现在我有了州和县的列表,我可以应用raqib的解决方案:

list_of_headings = ['state', 'county']
fipsDic = []
print len(list)
for i in range(len(list)):
    temp = {}
    for j in range(len(list[i])):
        tempDic[list_of_headings[j]] = list[i][j]

    fipsDic.append(temp)

结果是一个不错的字典列表,看起来像这样:

[{'county': 'Minnehaha County', 'state': 'SD'}, {'county': 'Minnehaha County', 'state': 'SD', ...}]
相关问题