如何将多个dict添加到一个倍数?

时间:2018-04-19 13:54:23

标签: python python-3.x dictionary

我想要一个像这样的词典:

dict_a= {
 'abc' : {'a':[1,2,3], 'b':[4,5,6], 'c':[7,8,9]},
 'efg' : {'a':[10,11,12], 'b':[13,14,15], 'c':[16,17,18]},
 'hij' : {'a':[21,22,23], 'b':[24,25,26], 'c':[27,28,29]}
}

所以我分成了2个词典

dict_b = {
 'a': [],
 'b': [],
 'c': []
}

dict_a= {
 'abc': {},
 'efg': {},
 'hij'
}

当我使用for循环放置数据时,最后一个数据将覆盖早期数据。以下是我的代码:

for x in sorted(dict_a):
    for y in sorted(dict_b):
        list= []
        ...
        dict_b[y] = list
    dict_a[x] = dict_b

结果是:

dict_a= {
     'abc' : {'a':[21,22,23], 'b':[24,25,26], 'c':[27,28,29]},
     'efg' : {'a':[21,22,23], 'b':[24,25,26], 'c':[27,28,29]},
     'hij' : {'a':[21,22,23], 'b':[24,25,26], 'c':[27,28,29]}
    }

我的预期结果是:

dict_a= {
 'abc' : {'a':[1,2,3], 'b':[4,5,6], 'c':[7,8,9]},
 'efg' : {'a':[10,11,12], 'b':[13,14,15], 'c':[16,17,18]},
 'hij' : {'a':[21,22,23], 'b':[24,25,26], 'c':[27,28,29]}
}

我该如何解决?

更新完整代码:

for market in sorted(MARKET_LUT):
        for type in sorted(STOCK_TYPE_LUT):
            try:
                list = []
                data = pd.read_csv(file_path, sep=' ', header=None, names=['code', 'name'])
                list = data.code.tolist()
                dict_b [type] = list 

            except Exception as e:
                traceback.print_exc()
                err = sys.exc_info()[1]
                LOG_write_log(LOG_ERROR, str(err))    

        dict_a[x] = dict_b

2 个答案:

答案 0 :(得分:0)

替换

for x in sorted(dict_a):
    for y in sorted(dict_b):
        list= []
        ...
        dict_b[y] = list
    dict_a[x] = dict_b

通过

for x in sorted(dict_a):
    new_dict = dict()
    for y in sorted(dict_b):
        list= []
        ...
        new_dict[y] = list
    dict_a[x] = new_dict

答案 1 :(得分:0)

我无法得到您想要的确切结果,但这似乎很接近并说明了如何避免您对上一次数据覆盖早期数据的问题。

from pprint import pprint

dict_b = {
    'a': [],
    'b': [],
    'c': []
}

dict_a= {
    'abc': {},
    'efg': {},
    'hij': {}
}

count = 1
for x in sorted(dict_a):
    dict_temp = dict_b.copy()  # Copy empty dict.
    for y in sorted(dict_b):
        lst = list(range(count, count+3))
        dict_temp[y] = lst
        count += 3
    dict_a[x] = dict_temp

pprint(dict_a)

结果:

{'abc': {'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]},
 'efg': {'a': [10, 11, 12], 'b': [13, 14, 15], 'c': [16, 17, 18]},
 'hij': {'a': [19, 20, 21], 'b': [22, 23, 24], 'c': [25, 26, 27]}}