Hi I'm trying to create nested dictionary which is supposed to look like:
{'4/1': {'A': 5, 'B': 6}, '4/2': {'A': 1, , 'B': 7}, '4/3': {'A': 4, 'B': 3}}
What I'm getting is:
{'4/1': {'A': 5}, '4/2': {'A': 1}, '4/3': {'A': 4}}
Code:
import random
import datetime as dt
futuresIncome = {}
incomeTypes = ["A", "B"]
for incomeType in incomeTypes:
for month in range(4, 5):
for day in range(1, 4):
date = str(month) + "/" + str(day)
if date in futuresIncome.keys():
continue
else:
futuresIncome[date] = {}
futuresIncome[date][incomeType] = random.randint(1, 11)
What am I doing wrong? Thank you.
"A", then on the next iteration (B) you then check if the key is there (which it is) and thencontinue, so your second iteration doesn't do anything. Try usepdbto debug this, you'll see that you always hit thecontinuepath once you get to the B iteration.futuresIncome[date] = {}, consider using adefaultdict(dict)instead. And you can changedate = str(month) + "/" + str(day)todate = f"{month}/{day}"