python字典 Dictionary
#-*- coding:UTF-8 -*- tel={'jack':4098,'sape':4139} tel['guido']=4127 print tel #{'sape': 4139, 'jack': 4098, 'guido': 4127} print tel['jack'] #4098 #如果key不存在会报错,避免key不存在的错误,有两种办法,一是通过in判断key是否存在 print 'guido' in tel #True #二是通过dict提供的get方法,如果key不存在,可以返回None,或者自己指定的value print tel.get('jilk') print tel.get('jilk',-1) #None #-1 del tel['sape'] tel['irv']=4127 print tel #{'jack': 4098, 'irv': 4127, 'guido': 4127} #要删除一个key,用pop(key)方法,对应的value也会从dict中删除 tel.pop('irv') print tel #{'jack': 4098, 'guido': 4127} print tel.keys() #['jack', 'guido'] #The dict() constructor builds dictionaries directly from sequences of key-value pairs: #dict() 函数用于创建一个字典。返回一个字典 print dict([('sape',4139),('guido',4127),('jack',4098)]) #{'sape': 4139, 'jack': 4098, 'guido': 4127} print {x:x**2 for x in (2,4,6)} #{2: 4, 4: 16, 6: 36} print dict(sape=4139,guido=4127,jack=4098) #{'sape': 4139, 'jack': 4098, 'guido': 4127}