[英]Python Dict Key Error. How do I loop through nested dict and check for a key
[英]Why do i get a Key Error in my Nested Dict
我正在嘗試對所有年份的收入以及其中的月份進行概覽,以查看我添加它們后收入的變化情況。
jahre = 3
monate = 12
mydict = {}
a = 1
b = 1
aa = 00
uu = 0
for oo in range(jahre):
mydict[str(a)] = str(uu)
for wu in range(monate):
mydict[jahre][str(b)] = {}
b = b + 1
a = a + 1
print(mydict)
我得到的 Output 是:
mydict[jahre][str(b)] = {}
KeyError: 1
首先,在您的代碼中, mydict[1]
不存在,因此 KeyError。 請注意, mydict["1"]
確實存在,因為您在第一個 for 循環中設置了它。
然而,這不是創建您想要獲取的字典的最佳方式,並且您的代碼將無法正常工作。
這是實現您想要做的事情的分解方法。
# first, let's set the variables for years and months, as you want 3 years and 12 months in each year
years = 3
months = 12
# then, let's initialise the dictionary
mydict = {}
# now comes the code to fill this dictionary
# first, we have a for loop over the years to generate the first level of the nested dictionary
# note that we use range(1, years+1) and not range(years) because range(years) iterate over 0, 1 and 2 and we want it to iterate over 1, 2 and 3
for year in range(1, years+1):
# for each year, we want to generate a key
# here, we set the "Year N." with the year number at the end
# so, for each year in the loop, it will create a key whose value will be, for instance, "Year N.1"
mydict["Year N."+str(year)] = {}
# now let's do the same but for months
# the same logic applies here, we iterate over each month
for month in range(1, months+1):
# now, we create a key for the month within the desired year
# note that here, the variable year is still the one over which it iterates in the first loop
# in the same way, we create each key like "Month N.11" for instance
mydict["Year N."+str(year)]["Month N."+str(month)] = {}
這段沒有注釋的代碼給了我們:
years = 3
months = 12
mydict = {}
for year in range(1, years+1):
mydict["Year N."+str(year)] = {}
for month in range(1, months+1):
mydict["Year N."+str(year)]["Month N."+str(month)] = {}
最后,嵌套字典mydict
將如下所示:
{'Year N.1': {'Month N.1': {},
'Month N.2': {},
'Month N.3': {},
'Month N.4': {},
'Month N.5': {},
'Month N.6': {},
'Month N.7': {},
'Month N.8': {},
'Month N.9': {},
'Month N.10': {},
'Month N.11': {},
'Month N.12': {}},
'Year N.2': {'Month N.1': {},
'Month N.2': {},
'Month N.3': {},
'Month N.4': {},
'Month N.5': {},
'Month N.6': {},
'Month N.7': {},
'Month N.8': {},
'Month N.9': {},
'Month N.10': {},
'Month N.11': {},
'Month N.12': {}},
'Year N.3': {'Month N.1': {},
'Month N.2': {},
'Month N.3': {},
'Month N.4': {},
'Month N.5': {},
'Month N.6': {},
'Month N.7': {},
'Month N.8': {},
'Month N.9': {},
'Month N.10': {},
'Month N.11': {},
'Month N.12': {}}}
如果答案不夠清楚,請隨時詢問。 我強烈建議您在解釋器中運行此代碼,這樣您可以查看每次迭代中變量發生的情況,以便在您無法從代碼和注釋中理解它的情況下更好地理解它是如何工作的。 您可以為此使用OnlineGDB 的解釋器及其調試選項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.