字典基础

# 字典输入使用{}
>>> cat={'size':'big','color':'white'}   #‘size’、‘color’为键
>>> cat['size']    #可通过键访问值
'big'
>>> spam={123:'aaa',46:'bb'}
>>> spam[123]       #可以用整数做键(事实上可用任意(数据类型)值的值做键)
'aaa'
#字典表项不排序
>>> cat={'size':'big','color':'white'} >>> dog={'color':'white','size':'big'} >>> cat==dog True

#列表表项排序
>>> a=['cat','dog'] >>> b=['dog','cat'] >>> a==b False

spam={'color':'white','size':'big'}
①值
for v in spam.values():    
    print(v)

white
big

②键
for k in spam.keys():
    print(k)

color
size

③键-值对
for i in spam.items():
    print(i)

('color', 'white')
('size', 'big')

④多重赋值

>>> for k,v in spam.items():
print('Key: '+k+' Value: '+v)

Key: color Value: white
Key: size Value: big
#利用字典得到列表
>>> spam={'color':'white','size':'big'}
>>> list(spam.keys())
['color', 'size']
#检查字典中是否存在键或值
>>> spam={'color':'white','size':'big'}
>>> 'color' in spam.keys()
True
>>> 'color' in spam   #上条的等价简写版(可能在value中,所以准确度依情况而定)
True
>>> 'age' not in spam.keys()
True
#get()方法    #get(x,y),如果键x不存在,则返回备用值y
>>> spam={'color':'white','size':'big'}
>>> print('My cat has '+str(spam.get('color',0))+' fur.')
My cat has white fur.
>>> print('My cat is '+str(spam.get('age',0))+' years old.')
My cat is 0 years old.
#若不适用get()代码就报错,因为不存在‘age’键
>>> spam={'color':'white','size':'big'}
>>> print('My cat is '+str(spam['age'])+' years old.')
Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    print('My cat is '+str(spam['age'])+' years old.')
KeyError: 'age'
#setdefault() 
>>> spam={'color':'white','size':'big'}
>>> spam.setdefault('age',2)   #setdefault(x,y)
2
>>> spam
{'color': 'white', 'size': 'big', 'age': 2}   #检查x,若键x不存在,就使用y为其值
>>> spam.setdefault('age',5)
2
>>> spam
{'color': 'white', 'size': 'big', 'age': 2}   #若x存在,则返回原值

 

posted @ 2023-02-15 17:05  Lucass-  阅读(19)  评论(0)    收藏  举报