Pythonic Way to reverse nested dictionaries

后端 未结 5 1752
旧巷少年郎
旧巷少年郎 2020-12-14 11:46

I have a nested dictionary of people and item ratings, with people as the key. people may or may not share items. Example:

{
 \'Bob\' : {\'item1\':3, \'item2         


        
5条回答
  •  忘掉有多难
    2020-12-14 12:14

    I totally agree that Ryan Ginstrom's answer is the preferred way of doing this (for all practical purposes).

    But since the question also explicitely asks:

    Is it possible with a comprehension?

    I thought I'd chime in with a quick example as for how to do this with a list comprehension (it could be a good example for showing how nested list comphrehensions can quickly decrease readability).

    import itertools
    
    d = {
     'Bob' : {'item1':3, 'item2':8, 'item3':6},
     'Jim' : {'item1':6, 'item4':7},
     'Amy' : {'item1':6,'item2':5,'item3':9,'item4':2}
    }
    
    print dict([(x, dict([(k, d[k][x]) for k,v in d.items() if x in d[k]])) 
                for x in set(itertools.chain(*[z for z in d.values()]))])
    

提交回复
热议问题