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'}

 

posted @ 2022-08-06 14:34  小鲨鱼2018  阅读(162)  评论(0编辑  收藏  举报