开发者

Python: How to construct a tuple, value dictionary from a list of key,value dictionary?

I have a list of dicts as follows:

lst = [{'unitname':'unit1', 'test1': 2, 'test2': 9}, {'unitname':'unit2', 'test1': 24, 'test2': 35}]

How do I contruct a single dict as follows:

dictA = { ('unit1','test1'): 2, ('unit1','test2'): 9, ('unit2','test1'):24, ('unit2','test2' : 35 }

`

I have all the unit names & test names in a list:

unitnames = ['unit1','unit2']
testnames = ['test1','test2']

I tried but missed out some tests for some units.

dictA = {}
for unit in unitnames:
    for dict in lst:
        for开发者_如何学编程 k,v in dict.items():
            dictA[unit,k] = v

Advices? Thanks.


dict(((d['unitname'], k), t)
     for d in lst
     for (k, t) in d.iteritems()
     if k != 'unitname')


You could try:

dictA = {}
for l in lst:
  name = l.pop('unitname')
  for test in l:
      dictA[name, test] = l[test]

Posted at the same time and with the same assumptions as Gareth's solution - however this will not give you the extra item of (name, 'unitname') = name


Marcelo Cantos's solution is quite elegant, but would be easier for mere mortals like us to parse like this:

dict(     ((d['unitname'], k), t)
     for d in lst
       for (k, t) in d.iteritems()
         if k != 'unitname'
    )


dictA = {}
for d in lst:
    unit = d['unitname']
    for test in testnames:
        if test in d:
            dictA[unit,test] = d[test]

I'm assuming (1) that all the dicts in your list have a unitname key, (2) that its value is always one of the units you're interested in, (3) that some dicts in the list may have entries for tests you aren't interested in, and (4) that some tests you're interested in may be absent from some dicts in the list. Those assumptions are a bit arbitrary; if any happen to be wrong it shouldn't be hard to adjust the code for them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜