I am new to python so please excuse any dumb mistakes but after research, I can't figure this out. I am creating a dictionary from a list of days in the month taken from calendar. I had originally used dict.fromkeys()
but found this submission that convinced me to change to the dictionary comprehension statement I have. Then I give each value in the dictionary another dictionary that has the day of the week as the key and another dictionary as the value. This dictionary is taskDic which has chores as the keys and will hold people's names as the values.
My problem is that my last statement in my loops is assigning the same person to do trash (etc) for every day even though the loop is just on the first day. I believe there is something wrong with how I start the dictionary because it is assigning values to all the dics as if they are the same.
Basically I have the same problem as the linked issue above but with nested dictionaries. Please let me know if I need to clarify anything. Thank you!
import calendar
week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
taskDic = {'Trash':[], 'Groceries':[], 'Clean':[]}
teamList = ['Jane', 'Peter', 'Jake', 'Eliza', 'Sarah', 'Bill']
person = 0
cal = list(calendar.Calendar().itermonthdays(2015, 8))
cal = {k: {} for k in cal}
for i in cal:
cal[i] = {week[i % 7]: taskDic}
for i in cal:
if (cal[i].keys() != 'Saturday') and (cal[i].keys() != 'Sunday'):
for j in cal[i]:
for k in cal[i][j]:
cal[i][j][k] = teamList[person % len(teamList)]
person += 1
My result looks like this:
0 {'Monday': {'Trash': 'Eliza', 'Groceries': 'Sarah', 'Clean': 'Bill'}}
1 {'Tuesday': {'Trash': 'Eliza', 'Groceries': 'Sarah', 'Clean': 'Bill'}}
2 {'Wednesday': {'Trash': 'Eliza', 'Groceries': 'Sarah', 'Clean': 'Bill'}}
3 {'Thursday': {'Trash': 'Eliza', 'Groceries': 'Sarah', 'Clean': 'Bill'}}
etc...
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…