Pythonic Way to reverse nested dictionaries

后端 未结 5 1749
旧巷少年郎
旧巷少年郎 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

    If you want just access reverse nested dictionaries, Save memory if the dictionary is too large to reverse.

    class mdict2(dict):
        def __init__(self, parent, key1):
            self.parent = parent
            self.key1 = key1
    
        def __getitem__(self, key2):
            return self.parent.mirror[key2][self.key1]
    
    
    class mdict(dict):
        def __init__(self, mirror):
            self.mirror = mirror
    
        def __getitem__(self, key):
            return mdict2(self, key)
    
    d0 = {
     'Bob' : {'item1':3, 'item2':8, 'item3':6},
     'Jim' : {'item1':6, 'item4':7},
     'Amy' : {'item1':6,'item2':5,'item3':9,'item4':2}
    }
    d1 = mdict(d0)
    
    d0['Amy']['item1'] == d1['item1']['Amy']
    # True
    

提交回复
热议问题