3

I have 5 lists and I want to map them to a hierarchical dictionary.

let's say i have:

temp = [25, 25, 25, 25]
volt = [3.8,3.8,3.8,3.8]
chan = [1,1,6,6]
rate = [12,14,12,14]
power = [13.2,15.3,13.8,15.1]

and what I want as my dictionary is this:

{25:{3.8:{1:{12:13.2,14:15.3},6:{12:13.8,14:15.1}}}}

Basically the dictionary structure is:

{temp:{volt:{chan:{rate:power}}}}

I tried using the zip function but it does not help in this case because of the repeated values in the list at the top level

Blender
  • 289,723
  • 53
  • 439
  • 496
emad
  • 2,869
  • 3
  • 18
  • 18
  • How do you handle the repeated values? – Blender Sep 25 '12 at 20:17
  • I just wanted to keep the list small in the example but my data will include for example: temp = [25,25,....,25,60,60,.....,60,75,75,...] The only reason I have these repeated values is because the power values correspond to that temp value...I have no use for the list once it is mapped to a dict. – emad Sep 25 '12 at 20:19
  • it is determined by the index. As an example for index = 2, temp = 25, volt = 3.8, chan = 1, rate = 14, power = 15.3 – emad Sep 25 '12 at 20:35

2 Answers2

8

This is only slightly tested, but it seems to do the trick. Basically, what f does, is to create a defaultdict of defaultdicts.

f = lambda: collections.defaultdict(f)
d = f()
for i in range(len(temp)):
    d[temp[i]][volt[i]][chan[i]][rate[i]] = power[i]

Example:

>>> print d[25][3.8][6][14]
15.1

(The idea is borrowed from this answer to a related question.)

Community
  • 1
  • 1
tobias_k
  • 81,265
  • 12
  • 120
  • 179
2

You can try the following ... I believe it serves what you want

>>> # Given your sample data.
>>> ans = {}
>>> for (t, v, c, r, p) in zip(temp, volt, chan, rate, power):
...     if not t in ans:
...             ans[t] = {}
...     if not v in ans[t]:
...             ans[t][v] = {}
...     if not c in ans[t][v]:
...             ans[t][v][c] = {}
...     if not r in ans[t][v][c]:
...             ans[t][v][c][r] = p
>>> print ans
{25: {3.8: {1: {12: 13.2, 14: 15.3}, 6: {12: 13.8, 14: 15.1}}}}
Mahmoud Aladdin
  • 536
  • 1
  • 3
  • 13