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

Updating a dictionary with values and predefined keys

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

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'},....
]

我对你的问题做了一些假设。您在评论中提到州在索引 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)

Raqib 的回答部分正确,但必须 mod 验证才能与包含行和列以及 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', ...}]