matteo
matteo

Reputation: 4873

Compact list of dictionaries into into single dictionary?

I have a list of dictionaries like the following:

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]}]

in this specific case the list has 19 dictionaries with 3 different keys (0,1,2).

What I'm trying to do is to transform it into a single dictionary where the values of each key is made by another dictionary.

So for example, extracting 4 elements of the list, I'd like to compact this:

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

into:

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

I hope I made myself clear

Upvotes: 3

Views: 900

Answers (2)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48067

You may get this result using collections.defaultdict as:

from collections import defautdict

my_dict = defaultdict(dict)

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

where my_dict will hold the final value as:

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

Note: Since dict can have unique keys, it will have the value of nested dict based on the last value in the list.

Upvotes: 2

georgedeath
georgedeath

Reputation: 414

This'll work, hopefully the code should be fairly self-explanatory.

Note that you'll need to use dictionary.iteritems() in Python 2.x, as dictionary.items() is Python 3.x only.

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

Upvotes: 2

Related Questions