简介:
我正在尝试访问python中的嵌套字典元素,如下所示:
{'CA':{'1':'3','2':'3','3':'3'},'IL': {'1':'31','2':'45','3':'23'},...}
首先,我从Excel文件中读取,我获取状态名称,然后为每个州分配字典。我就是这样做的:
xls_file = pd.ExcelFile('D:/CollegeScorecardDataDictionary-08-18-2016.xlsx')
dfEx = xls_file.parse('Church') # Parse Church sheet
for (i, item) in enumerate(stateName):
if stateChurchDict.get(item)<>None:
continue
else:
stateChurchDict[item] = dict
一旦迭代循环,我就会这样:
{'CA':<type dict>,'IL': <type dict>,'AL': <type dict>...}
在每个州都有很多教堂可以归类为'1', '2' or '3'
这是我在嵌套字典中获得数字的地方。
我的问题是我想引用某些状态的嵌套字典,如
stateChurchDict['AL']['3']
并获得类别&#39; 3&#39;下的教堂数量在某种状态下。但是,首先我必须检查它是否为空,如果它是空的,则必须添加该值。因此,我想出了这个:
for (i, item) in enumerate(stateName):
if stateChurchDict[stateName[i-1]]['3'] <> None:
stateChurchDict.update({stateChurchDict[stateName[i-1]]['3']: stateChurchDict[stateName[i-1]]['3'] + 1})
else:
stateChurchDict[stateName[i-1]]['3'] = 1
但是,stateChurchDict[stateName[i-1]]['3']
这个stateName[i-1] == 'AL'
无法访问嵌套字典stateChurchDict['AL']['3']
,它会调用像import pandas as pd
from collections import defaultdict, Counter
def IsNumeric(x):
try:
float(x)
return x
except:
return 0
xls_file = pd.ExcelFile('D:/CollegeScorecardDataDictionary-08-18-2016.xlsx')
dfEx = xls_file.parse('Church') # Parse data_dictionary sheet
dfCsv = pd.read_csv('D:/MERGED2014_15_PP.csv', low_memory=False)
churchCode = dfEx.Code # Label column
churchName = dfEx.ChurchName # Value column
churchCategory = dfEx.Category # Church category
relafil = dfCsv.RELAFFIL # Religious Id in CSV
stateName = dfCsv.STABBR # Name of state
churchList = {} # Create dictionary to store churches
stateChurchDict = defaultdict(Counter) # Create dictionary to store churches by state
stateChurchTemp = {} #Sepate dictionary for churches by state
# Put values into dictionary
for (i, v) in enumerate(churchCode):
churchList[v] = churchCategory[i] #Assigns a category to each church in state
for (i, item) in enumerate(stateName): #Create a dictionary as a value to each state in the stateChurchList dictionary
if item <> None:
if stateChurchDict.get(item) <> None:
continue
else:
stateChurchDict[item] = {}
for (i, item) in enumerate(stateName): #Iterate through states and count the number of churches by categories. Once the state name is changed, the number needs to be transferred from stateChurchTemp to stateChurchDict
if IsNumeric(relafil[i]) <> 0:
if i >= 1 and item <> stateName[i - 1]:
if stateChurchDict[stateName[i - 1]][3] <> None:
stateChurchDict.update({stateChurchDict[stateName[i - 1]][3]: stateChurchDict[stateName[i - 1]][
3] + IsNumeric(
stateChurchTemp[3])})
else:
stateChurchDict[stateName[i - 1]][3] = IsNumeric(stateChurchTemp[3])
if stateChurchDict[stateName[i - 1]][2] <> None:
stateChurchDict.update({stateChurchDict[stateName[i - 1]][2]: stateChurchDict[stateName[i - 1]][
2] + IsNumeric(
stateChurchTemp[2])})
else:
stateChurchDict[stateName[i - 1]][2] = IsNumeric(stateChurchTemp[2])
if stateChurchDict[stateName[i - 1]][1] <> None:
stateChurchDict.update({stateChurchDict[stateName[i - 1]][1]: stateChurchDict[stateName[i - 1]][
1] + IsNumeric(
stateChurchTemp[1])})
else:
stateChurchDict[stateName[i - 1]][1] = IsNumeric(stateChurchTemp[1])
if churchList.get(relafil[i]) <> None and stateChurchTemp.get(churchList.get(relafil[i])) <> None:
stateChurchTemp.update({churchList.get(relafil[i]): stateChurchTemp.get(churchList.get(relafil[i])) + 1})
else:
stateChurchTemp[churchList.get(relafil[i])] = 1
print stateChurchDict
这样的元素,但仍然没有。
非常感谢任何帮助。
我发布了所有内容以获得更好的解释:
def reverse(arr):
for i in range(len(arr) / 2):
arr[-i-1], arr[i] = arr[i], arr[-i-1]
答案 0 :(得分:1)
stateChurchDict
首先应该不是 vanilla 字典。
传递给collections.Counter
的collections.defauldict
是正确的方向:
>>> from collections import defaultdict, Counter
>>> d = defaultdict(Counter) # or defaultdict(lambda: defaultdict(int))
>>> d['AL']['3']
0
使用此功能,可以动态生成默认计数值,以便最多嵌套两个级别的密钥,并且您的代码将减少为:
from collections import defaultdict, Counter
stateChurchDict = defaultdict(Counter)
for i, item in enumerate(stateName):
stateChurchDict[stateName[i-1]]['3'] += 1
答案 1 :(得分:1)
好的,这就是我的回答。简单地说,我创建了另一个字典internalDict
,它存储了嵌套字典的值。
我没有致电stateChurchDict[stateName[i-1][3]]
,而是尝试了internalDict = stateChurchDict[stateName[i-1]]
,之后只与internalDict
合作。因此,调用stateChurchDict[stateName[i-1][3]]
就像internalDict[3]
。
答案 2 :(得分:1)
您没有调用嵌套字典,而是尝试更新主字典。请更改此行:
stateChurchDict.update({stateChurchDict[stateName[i - 1]][2]: stateChurchDict[stateName[i - 1]][2] + IsNumeric(stateChurchTemp[2])})
用这个:
stateChurchDict.get(statename[i-1]).update({3: stateChurchDict[stateName[i - 1]][3] + IsNumeric(stateChurchTemp[3])})