给定一本这样的字典:
my_map = {'a': 1, 'b': 2}
如何将此映射颠倒得到:
inv_map = {1: 'a', 2: 'b'}
给定一本这样的字典:
my_map = {'a': 1, 'b': 2}
如何将此映射颠倒得到:
inv_map = {1: 'a', 2: 'b'}
当前回答
dict([(value, key) for key, value in d.items()])
其他回答
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
dict([(value, key) for key, value in d.items()])
函数对于list类型的值是对称的;执行reverse_dict(reverse_dict(dictionary))时,元组被转换为列表
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
试试这个:
inv_map = dict(zip(my_map.values(), my_map.keys()))
(请注意,字典视图上的Python文档显式保证.keys()和.values()的元素顺序相同,这允许上述方法工作。)
另外:
inv_map = dict((my_map[k], k) for k in my_map)
或者使用python 3.0的字典推导式
inv_map = {my_map[k] : k for k in my_map}