‘’’
字典:contacts={‘键’:‘值’} 由于键不可变,so只能用不可变的数据类型 可有append、remove方法,del(‘键’)、‘键’ in contacts
列表:list=[1,2,3,4] 不可以做键 可有append、remove方法
(列表属于可变数据类型,所以不可以做键)
元组:tuple=(1,2,3,4) 可以做键 无方法
‘’’
#案例
‘’‘练习6-1:
使用一个字典来存储一个熟人的信息,包括名、姓、年龄和居住的城市。该字典应包含键first_name、last_name、age和city。
将存储在该字典中的每项信息都打印出来。’‘’
dictionary={'first_name':'婵','last_name':'王','age':23,'city':'保定'}
print('姓名:'+dictionary['last_name']+dictionary['first_name']+' 年龄:'+dictionary['age'].__str__()+' 城市:'+dictionary['city'])
‘’‘字典对应的方法:
contacts.keys() #所有键
contacts.values() #所有值
contacts.items() #所有键值对
‘’’
print(dictionary.items())
print(dictionary.keys())
print(dictionary.values())
‘’‘练习6-5:河流
创建一个字典,在其中存储三条重要河流及其流经的国家例如,一个键值对可能是’nile’: ‘egypt’ 。
-使用循环为每条河流打印一条消息,下面是一个例子。The Nile runs through Egypt.
-使用循环将该字典中每条河流的名字打印出来。-使用循环将该字典包含的每个国家的名字打印出来。
‘’’
Rivers={'nile':'egypt','HuangHe':'China','LanCangJiang':'UK'}
for name,country in Rivers.items():
print('The '+name+' runs through '+country)
for Rivers_tuple in Rivers.items():
print('河流:'+Rivers_tuple[0])
print('国家:' + Rivers_tuple[1])