matteo - 1 year ago 68
Python Question

# 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

Answer Source

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
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download