紧凑的字典列表成单个字典?

时间:2016-11-22 15:18:31

标签: python list dictionary

我有一个字典列表,如下所示:

l = [{0: [1L, 743.1912508784121]}, {0: [2L, 148.34440427559701]}, {0: [5L, 1275.9155165676464]}, {0: [6L, 128.46132477853394]}, {0: [8L, 1120.5549823618721]}, {0: [9L, 1000.4359061629533]}, {0: [10L, 1000.4359061629533]}, {0: [11L, 1148.2027994669606]}, {0: [12L, 222.1206974476257]}, {0: [15L, 1024.0437005257695]}, {1: [8L, 606.0185176629063]}, {1: [13L, 115.54464589045607]}, {1: [14L, 1057.134622491455]}, {1: [16L, 1000.346200460439]}, {1: [17L, 285.73897308106336]}, {2: [3L, 941.8651982485691]}, {2: [4L, 1001.6313224538114]}, {2: [7L, 1017.0693313362076]}, {2: [11L, 427.7241587977401]}]

在这种特定情况下,该列表包含19个带有3个不同键(0,1,2)的词典。

我尝试做的是将其转换为单个词典,其中每个键的值由另一个词典创建。

例如,提取列表中的4个元素,我想压缩它:

   l = [{0: [1L, 743.1912508784121]}, {0: [2L, 148.34440427559701]}, {1: [13L, 115.54464589045607]}, {1: [14L, 1057.134622491455]}]

成:

   d = {0:{1L: 743.1912508784121, 2L: 148.34440427559701}, 1:{13L: 115.54464589045607, 14L: 1057.134622491455}}

我希望自己清楚明白

2 个答案:

答案 0 :(得分:2)

这可行,希望代码应该是相当不言自明的。

请注意,您需要在Python 2.x中使用dictionary.iteritems(),因为dictionary.items()仅限Python 3.x。

d ={}
for dictionary in l:
    for key, (k, v) in dictionary.items():
        if key not in d:
            d[key] = {}
        d[key][k] = v

答案 1 :(得分:2)

您可以使用collections.defaultdict获取此结果:

from collections import defautdict

my_dict = defaultdict(dict)

for d in l:
    for k, (v1, v2) in d.items():
        my_dict[k][v1] = v2

其中my_dict将最终值保存为:

{0: {1L: 743.1912508784121, 2L: 148.34440427559701, 5L: 1275.9155165676464, 6L: 128.46132477853394, 8L: 1120.5549823618721, 9L: 1000.4359061629533, 10L: 1000.4359061629533, 11L: 1148.2027994669606, 12L: 222.1206974476257, 15L: 1024.0437005257695}, 1: {8L: 606.0185176629063, 16L: 1000.346200460439, 13L: 115.54464589045607, 14L: 1057.134622491455, 17L: 285.73897308106336}, 2: {11L: 427.7241587977401, 3L: 941.8651982485691, 4L: 1001.6313224538114, 7L: 1017.0693313362076}}

注意:由于dict可以有唯一的key,因此根据{{1}中的最后一个值,它将具有嵌套dict的值}}