字典的增删改查
info = {"name":"Poe"}#增info["age"] = 18info["qq"] = 33794712print(info) #{'age': 18, 'qq': 33794712, 'name': 'Poe'}#删del info['qq']print(info) #{'age': 18, 'name': 'Poe'}#如果字典中没有这个键,那么程序会抛出异常#查print(info['name']) #Poe#如果没有name键会抛出异常print(info.get('name')) #Poe#如果没有name键不会抛出异常,返回空#改info['name'] = 'andy'print(info) #{'age': 18, 'name': 'andy'}
for else语句
nums = [11,22,33,44,55]for temp in nums: print(nums)else: print("="*10)#else中的语句是for循环结束后执行
有关字典的遍历
info = {"name":"poe","age":18,"addr":"Hongkong"}print(len(info)) #3print(info.keys()) #dict_keys(['name', 'addr', 'age'])print(info.values()) #dict_values([18, 'poe', 'Hongkong'])#注:以上是python3得到的结果,python2中只返回其中的列表部分for key in info.keys(): print(key)for value in info.values(): print(value)print(info.items()) #dict_items([('addr', 'Hongkong'), ('name', 'poe'), ('age', 18)])for temp in info.items(): print("key=%s,value=%s" % (temp[0],temp[1]))"""输出结果:key=addr,value=Hongkongkey=age,value=18key=name,value=poe""" #注意元组的下面这种使用方法a = (11,22)b,c = aprint(b,c) #11 22for A,B in info.items(): print("key=%s,value=%s" % (A,B))'''输出结果:key=age,value=18key=addr,value=Hongkongkey=name,value=poe'''