Python ֵ(Dictionary)
ֵһN׃?ni)ģͣҿɴ惦͌ģͣ?h3>Python ֵ(Dictionary)
ֵI͌(yng)ֵɌMֵҲQP(gun)(lin)(sh)MϣZ£
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
Ҳ˄(chung)ֵ䣺
dict1 = { 'abc': 456 };dict2 = { 'abc': 123, 98.6: 37 };
ÿIcֵð̖_:ÿöָ̖wڻ̖У{}
I횪һoֵt
ֵȡκΔ(sh)(j)ͣDz׃ַ(sh)ԪM
Lֵֵ
(yng)IϤķ:
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; print "dict['Name']: ", dict['Name'];print "dict['Age']: ", dict['Age'];
όݔY(ji)
dict['Name']: Zaradict['Age']: 7
ֵ]еIL(sh)(j)ݔe`£
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; print "dict['Alice']: ", dict['Alice'];
όݔY(ji)
dict['Zara']:Traceback (most recent call last): File "test.py", line 4, in<module>print "dict['Alice']: ", dict['Alice'];KeyError: 'Alice'</module>
ֵ
ֵ(ni)ݵķµI/ֵĻhI/ֵ:
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; dict['Age'] = 8; # update existing entrydict['School'] = "DPS School"; # Add new entry print "dict['Age']: ", dict['Age'];print "dict['School']: ", dict['School'];όݔY(ji)
dict['Age']: 8dict['School']: DPS School
hֵԪ
܄hһԪҲֵ䣬ֻһ헲
@ʾhһֵdel
#!/usr/bin/python# -*- coding: UTF-8 -*-dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; del dict['Name']; # hI'Name'ėlĿdict.clear(); # ~ЗlĿdel dict ; # h~ print "dict['Age']: ", dict['Age'];print "dict['School']: ", dict['School'];
@l(f)һdelֵ䲻ٴڣ
dict['Age']:Traceback (most recent call last): File "test.py", line 8, in<module>print "dict['Age']: ", dict['Age'];TypeError: 'type' object is unsubscriptable</module>
עdel()ҲӑՓ
XY
Python ֵ(Dictionary)(http://m.dameics.com)
hֵԪ
ֵI
ֵֵԛ]Ƶȡκpythonȿǘ(bio)(zhn)ČҲÑxI
ɂҪcҪӛ
1SͬһIF(xin)ɴΡ(chung)rͬһIxֵɴһֵӛס
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}; print "dict['Name']: ", dict['Name'];
όݔY(ji)
dict['Name']: Manni
2I횲׃ԿÔ(sh)ַԪM䮔(dng)бͲ
#!/usr/bin/python dict = {['Name']: 'Zara', 'Age': 7}; print "dict['Name']: ", dict['Name'];
όݔY(ji)
Traceback (most recent call last): File "test.py", line 3, in<module>dict = {['Name']: 'Zara', 'Age': 7};TypeError: list objects are unhashable</module>
ֵ(ni)ú(sh)&
Pythonֵ(ni)ú(sh)
^ɂֵԪ2len(dict)
ӋֵԪ(sh)IĿ(sh)3str(dict)
ݔֵɴӡַʾ4type(variable)
ݔ׃׃ֵͷֵ
Pythonֵ(ni)ú(sh)
hֵ(ni)Ԫ2radiansdict.copy()
һֵĜ\(f)3radiansdict.fromkeys()
(chung)һֵseqԪֵIvalֵI(yng)ijʼֵ4radiansdict.get(key, default=None)
ָIֵֵֵзdefaultֵ5radiansdict.has_key(key)
Iֵdictﷵtruetfalse6radiansdict.items()
бؿɱv(I, ֵ) ԪM(sh)M7radiansdict.keys()
бһֵеI8radiansdict.setdefault(key, default=None)
get(), Iѽ(jng)ֵIֵO(sh)default9radiansdict.update(dict2)
ֵdict2I/ֵµdict10radiansdict.values()
бֵеֵ