python 字典中键和值的相互逆转
001、
>>> test1 = dict(a = 100, b = 200, c = 300, d = 400) >>> test1 {'a': 100, 'b': 200, 'c': 300, 'd': 400} >>> test2 = dict() >>> for i,j in test1.items(): ## 键、值逆转 ... if j not in test2: ... test2[j] = i ... >>> test2 {100: 'a', 200: 'b', 300: 'c', 400: 'd'}
002、
>>> test1 {'a': 100, 'b': 200, 'c': 300, 'd': 200, 'e': 200} >>> test1 {'a': 100, 'b': 200, 'c': 300, 'd': 200, 'e': 200} >>> test2 = dict() >>> for i,j in test1.items(): ## 字典的键不能为重复值 ... if j not in test2: ... test2[j] = i ... else: ... test2[str(j)+str(i)+'dup'] = i ... >>> test2 {100: 'a', 200: 'b', 300: 'c', '200ddup': 'd', '200edup': 'e'}

浙公网安备 33010602011771号