I tried to update main dictionary with every new one in the loop, but every time it overwrite values inside the nested dictionary. I mean I want smth like this:
{'Barbour': {1900: 73041, 1910: 895427, 1920: 1531624, 1930: 1617086, 1940: 1420561, 1950: 1853223,
1960: 3092728, 1970: 3505193, 1980: 3659797, 1990: 2575561, 2000: 743757, 2010: 1730711},
'Berkeley': {1900: 0, 1910: 0, 1920: 0, 1930: 0, 1940: 0, 1950: 0, 1960: 0, 1970: 0, 1980: 0, 1990:
0, 2000: 0, 2010: 0}}
(for all of the cities)
def read_file_contents_coal():
return ['Barbour,73041,895427,1531624,1617086,1420561,1853223,3092728,3505193,3659797,2575561,743757,1730711\n',
'Berkeley,0,0,0,0,0,0,0,0,0,0,0,0\n',
'Boone,0,50566,1477560,3045056,3804527,5851267,6278609,11607216,13842525,27618152,32446186,23277998\n',
'Braxton,0,114422,286955,123991,13751,38414,218087,0,459517,3256906,1196489,439662\n',
]
def process_file_contents():
lst = read_file_contents_coal()
dic = {}
coal_dic = {}
yearcoaldic = {}
ycdic = {}
for stringdata in lst:
city_data = stringdata.strip().split(',')
year = 1900
for j in range(1, 13):
ycdic = {year: int(city_data[j])}
year += 10
yearcoaldic.update(ycdic)
dic = {city_data[0]: yearcoaldic}
coal_dic.update(dic)
print(coal_dic)
return coal_dic
[EDIT]: the issue is that you have to move
yearcoaldic
to the first loop and always set it to en empty dictionary otherwise you will always overwrite your values as you have experienced.