Python No.15 字典

# !/usr/bin/env python# -*- coding:utf-8 -*-# Author:Hugolinhjinfo = {    'stu1101':'adbc',    'stu1102':'adef',    'stu1103':'aghi',}#'key':'value',鍵:值print(info)#字典沒有下標,打印順序會亂。print(info['stu1101'])#查看key對應的value值,但!不存在key,則報錯。print(info.get('stu1101'))#查看key對應的value值,但!不存在key,則不會報錯。推薦!!!info['stu1101']='ssss'print(info)info['stu1104']='aaaa'print(info)#修改key對應的value值,若是沒有則增長key-value。del info['stu1101']print(info)#或者:  info.pop('stu1102')  print(info)#'del'和'pop'都是刪除info.popitem()print(info)#隨機刪除。print('stud1104' in info)  # info.has_key('stud1104')在python2.x#判斷是否有該key,b = {    'stu1101':'zxcasd',    1:3,    2:5,}info.update(b)print(info)#更新key,沒有key則直接增長。print(info.items())#把字典轉化爲列表。c=info.fromkeys([1,7,8],'ss')print(info)#初始化新的字典。c[1]='ddd'print(c)#初始化新的字典。info = {    'stu1101':'adbc',    'stu1102':'adef',    'stu1103':'aghi',}for i in info:    print(i,info[i])#先循環打印key值,再打印對應value值。(推薦)for k,v in info.items():    print(k,v)#先轉列表,再打印
相關文章
相關標籤/搜索