假如“省份-城市”字典
citys={'hb':'wuhan',
'sc':'chengdu',
'gd':'guangzhou',
'gx':'nanning',
'hn':'changsha',}
1、如果字典“键-值对”中的键存在重复值时,无论是否使用集合(set)(函数set()),均不会打印重复的键:
citys={ 'hb':'wuhan',
'sc':'chengdu',
'gd':'guangzhou',
'gd':'shenzhen',
'hn':changsha',}
for province in citys.keys(): #没有使用集合(set)(函数set())
print(province)
打印结果:
hb
sc
gd
hn
citys={ 'hb':'wuhan',
'sc':'chengdu',
'gd':'guangzhou',
'gd':'shenzhen',
'hn':'changsha',}
for province in set(citys.keys()): #使用集合(set)(函数set())
print(province)
打印结果:
hb
sc
gd
hn
2、如果字典“键-值对”中的值存在重复值时,需要使用集合(set)(函数set())来剔除重复的值,否则会打印重复的值:
citys={ 'hb':'wuhan',
'sc':'chengdu',
'gd':'guangzhou',
'gx':'guangzhou',
'hn':'changsha',}
for city in citys.values(): #没有使用集合(set)(函数set())
print(city)
打印结果:
wuhan
chengdu
guangzhou
guangzhou
changsha
citys={ 'hb':'wuhan',
'sc':'chengdu',
'gd':'guangzhou',
'gx':'guangzhou',
'hn':'changsha',}
for city in set(citys.values()): #使用集合(set)(函数set())
print(city)
打印结果:
wuhan
chengdu
guangzhou
changsha
,