lst=[("triangle", "shape"),("red","color"),("square","shape"),("yellow","color"),("green","color"),("circle","shape")]
list1=dict(lst)
list2={}
for k,v in list1.items():
list2[v]=k
print(list2)
lst=[("triangle", "shape"),("red","color"),("square","shape"),("yellow","color"),("green","color"),("circle","shape")]
list1=dict(lst)
print(list1)
print('-'*14)
list2={}
for k,v in list1.items():
list2[v]=k
print(v,k)
print('-'*14)
print(list2)
看一下这个
list1=dict(lst)之后,都转成dict{'triangle': 'shape', 'red': 'color', 'square': 'shape', 'yellow': 'color', 'green': 'color', 'circle': 'shape'}
for k,v in list1.items():
list2[v]=k
注意 v,k调换
所以,for执行的
shape triangle
color red
shape square
color yellow
color green
shape circle
最后的结果,是key只有color,shape,value是最后的green,circle
在python的同一个字典中,key是唯一的,因为你在互换数据前,list1 = {'triangle': 'shape', 'red': 'color', 'square': 'shape', 'yellow': 'color', 'green': 'color', 'circle': 'shape'},所以在互换后,如果原value值相同的(新字典list2的key),会覆盖 list2 字典中已有的数据