给定一本这样的字典:
my_map = {'a': 1, 'b': 2}
如何将此映射颠倒得到:
inv_map = {1: 'a', 2: 'b'}
给定一本这样的字典:
my_map = {'a': 1, 'b': 2}
如何将此映射颠倒得到:
inv_map = {1: 'a', 2: 'b'}
当前回答
例如,你有以下字典:
my_dict = {'a': 'fire', 'b': 'ice', 'c': 'fire', 'd': 'water'}
你想要得到这样一个倒立的形式
inverted_dict = {'fire': ['a', 'c'], 'ice': ['b'], 'water': ['d']}
第一个解决方案。要在字典中反转键值对,请使用For循环方法:
# 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]}
其他回答
当前python 3的lambda解决方案。x版本:
d1 = dict(alice='apples', bob='bananas')
d2 = dict(map(lambda key: (d1[key], key), d1.keys()))
print(d2)
结果:
{'apples': 'alice', 'bananas': 'bob'}
此解决方案不检查重复项。
一些评论:
构造可以从外部作用域访问d1,所以我们只能 传入当前键。它返回一个元组。 dict()构造函数接受一个元组列表。它 也接受映射的结果,所以我们可以跳过转换到 列表。 这个解决方案没有显式的for循环。它还避免了对那些数学不好的人使用列表理解;-)
def invertDictionary(d):
myDict = {}
for i in d:
value = d.get(i)
myDict.setdefault(value,[]).append(i)
return myDict
print invertDictionary({'a':1, 'b':2, 'c':3 , 'd' : 1})
这将提供输出为:{1:(' a ', ' d '), 2: [b], 3: [' c ']}
与值不同,字典需要在字典中有一个唯一的键,因此我们必须将反向的值附加到一个sort列表中,以便包含在新的特定键中。
def r_maping(dictionary):
List_z=[]
Map= {}
for z, x in dictionary.iteritems(): #iterate through the keys and values
Map.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
有很多答案,但没有找到任何干净的东西,以防我们谈论的是一个具有非唯一值的字典。
解决办法是:
from collections import defaultdict
inv_map = defaultdict(list)
for k, v in my_map.items():
inv_map[v].append(k)
例子:
如果初始dict my_map ={“c”:1、“d”:5,' ':5 b: 10}
然后,运行上面的代码将得到:
{5: ['a', 'd'], 1: ['c'], 10: ['b']}
除了上面建议的其他函数,如果你喜欢lambdas:
invert = lambda mydict: {v:k for k, v in mydict.items()}
或者,你也可以这样做:
invert = lambda mydict: dict( zip(mydict.values(), mydict.keys()) )