Python的字典

來源:互聯網
上載者:User

標籤:get   方式   list   set   字典   轉換   官方   upd   文法   

#文法: {‘key‘:‘value‘,‘key1‘:‘value1‘}
names = {‘jhj‘:[18,‘女‘,‘東北‘],
‘zxf‘:{‘age‘:19,‘sex‘:‘男‘,‘addr‘:‘內蒙‘}
}

#增
#names[‘nhy‘]=[20,‘男‘,‘北京‘]#如果原來不存在新增,如果原來存在即覆蓋
#刪:3種方法,del,pop(),popitem(),前2種刪除一個不存在的值都會報錯,官方推薦用pop
del names[‘nhy‘]
names.pop(‘msr‘)
names.popitem()#隨機刪除一個key
#改
#names[‘jhj‘]=[18,‘女‘,‘北京‘]
#查:2種方式
#1.print(names[‘jhj‘])
#2.print(names.get(‘zxf‘))
#.get方法,查詢一個不存在的值時返回none,不會報錯,第一種會報錯
#內建方法:
print(names.keys())#返回字典所有key的值
print(names.values())#返回字典所有value的值
names.setdefault(‘msr‘:[‘女‘,‘18‘])#也可以賦值,和直接賦值的方式的區別在於,如果該值存在保持不變,如果不存在新增
new_names= {‘zzj‘:[‘18‘,‘bj‘]}
names.update(new_names)#擴充字典
print(names)
names.has_key(‘123‘)#判斷有無該key,Python2中有該方法,Python3中無此方法
print(‘zzj‘ in names)#python3可以通過這種方法判斷是否有這個key

for k in names: #列印key值
print(k)
for k in names.items():
print(k,v)#擷取字典中key和value對應的值
#names.items()把字典轉換成2個list
for k in names:
print(k,names[k])#擷取字典中key和value對應的值

Python的字典

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.