class ReversibleDict(dict):
def reversed(self):"""Return a reversed dict, with common values in the original dictgrouped into a list in the returned dict.
Example:>>> d = ReversibleDict({'a': 3, 'c': 2, 'b': 2, 'e': 3, 'd': 1, 'f': 2})>>> d.reversed(){1: ['d'], 2: ['c', 'b', 'f'], 3: ['a', 'e']}"""
revdict = {}for k, v in self.iteritems():revdict.setdefault(v, []).append(k)return revdict
def reverse_dict(dictionary):reverse_dict = {}for key, value in dictionary.iteritems():if not isinstance(value, (list, tuple)):value = [value]for val in value:reverse_dict[val] = reverse_dict.get(val, [])reverse_dict[val].append(key)for key, value in reverse_dict.iteritems():if len(value) == 1:reverse_dict[key] = value[0]return reverse_dict
class SymDict:def __init__(self):self.aToB = {}self.bToA = {}
def assocAB(self, a, b):# Stores and returns a tuple (a,b) of overwritten bindingscurrB = Noneif a in self.aToB: currB = self.bToA[a]currA = Noneif b in self.bToA: currA = self.aToB[b]
self.aToB[a] = bself.bToA[b] = areturn (currA, currB)
def lookupA(self, a):if a in self.aToB:return self.aToB[a]return None
def lookupB(self, b):if b in self.bToA:return self.bToA[b]return None
def r_maping(dictionary):List_z=[]Map= {}for z, x in dictionary.iteritems(): #iterate through the keys and valuesMap.setdefault(x,List_z).append(z) #Setdefault is the same as dict[key]=default."The method returns the key value available in the dictionary and if given key is not available then it will return provided default value. Afterward, we will append into the default list our new values for the specific key.return Map
def inverse(mapping):'''A function to inverse mapping, collecting keys with simillar valuesin list. Careful to retain original type and to be fast.>> d = dict(a=1, b=2, c=1, d=3, e=2, f=1, g=5, h=2)>> inverse(d){1: ['f', 'c', 'a'], 2: ['h', 'b', 'e'], 3: ['d'], 5: ['g']}'''res = {}setdef = res.setdefaultfor key, value in mapping.items():setdef(value, []).append(key)return res if mapping.__class__==dict else mapping.__class__(res)
for k, v in myDict.items():if len(v) > 1:for item in v:invDict[item] = invDict.get(item, [])invDict[item].append(k)else:invDict[v] = invDict.get(v, [])invDict[v].append(k)
使用递归,如果你需要深入挖掘,那么只需一个维度:
def digList(lst):temp = []for item in lst:if type(item) is list:temp.append(digList(item))else:temp.append(item)return set(temp)
for k, v in myDict.items():if type(v) is list:items = digList(v)for item in items:invDict[item] = invDict.get(item, [])invDict[item].append(k)else:invDict[v] = invDict.get(v, [])invDict[v].append(k)
# Use this code to invert dictionaries that have non-unique values
inverted_dict = dict()for key, value in my_dict.items():inverted_dict.setdefault(value, list()).append(key)
第二解决方案.使用字典理解方法进行反转:
# Use this code to invert dictionaries that have unique values
inverted_dict = {value: key for key, value in my_dict.items()}
第三种解决方案.使用恢复反转方法(依赖于第二个解决方案):
# Use this code to invert dictionaries that have lists of values
my_dict = {value: key for key in inverted_dict for value in my_map[key]}
def dict_invert(d):'''d: dictReturns an inverted dictionary'''# Your code hereinv_d = {}for k, v in d.items():if v not in inv_d.keys():inv_d[v] = [k]else:inv_d[v].append(k)inv_d[v].sort()print(f"{inv_d[v]} are the values")
return inv_d