mapping multiple lists to dictionary

前端 未结 2 1535
死守一世寂寞
死守一世寂寞 2021-01-20 17:32

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         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-20 18:08

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

提交回复
热议问题