如何在字典中交换键和值?

时间:2015-04-07 10:25:46

标签: python python-3.x dictionary

我想在给定的字典中交换键和值。例如:

dict = {1:'sandeep', 2: 'suresh', 3: 'pankaj'}

将成为:

dict1 = {'sandeep': 1, 'suresh': 2, 'pankaj': 3}

2 个答案:

答案 0 :(得分:0)

使用zip可能比字典理解更好:

dict1 = dict(zip(dict1.values(), dict1.keys())) # better for beginners

答案 1 :(得分:0)

In [45]: d = {1:'sandeep',2 : 'suresh', 3: 'pankaj'}

In [46]: {(v, k) for k,v in d.iteritems()}
Out[46]: {'pankaj': 3, 'sandeep': 1, 'suresh': 2}

请注意使用d作为变量名称而不是内置dict

另请注意,您无法保证唯一性并且可能会丢失条目:

In [47]: d = {1:'sandeep',2 : 'suresh', 3: 'pankaj', 4:'suresh'}

In [48]: {(v, k) for k,v in d.iteritems()}
Out[48]: {'pankaj': 3, 'sandeep': 1, 'suresh': 4}