0

我试图用循环中的每个新字典来更新主字典,但每次它都会覆盖嵌套字典中的值。我的意思是我想要这样的东西:

{'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}} 

(适用于所有城市)

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
4

1 回答 1

0

[编辑]:问题是您必须移至yearcoaldic第一个循环并始终将其设置为空字典,否则您将始终覆盖您所经历的值。

def process_file_contents():
    lst = read_file_contents_coal()
    dic = {}
    coal_dic = {}
    ycdic = {}
    for stringdata in lst:
        yearcoaldic = {}
        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}
        dic[city_data[0]] = yearcoaldic

    # coal_dic.update(dic)
    # print(coal_dic)
    return dic
于 2020-10-04T13:52:35.390 回答