Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。
1. 取值
d = {'name':'xiao','age':19,'sex':'男'}
print(d['name'])
2. 赋值
d = {'name':'xiao','age':19,'sex':'男'}
d['name'] = 'xiaoli'
print(d)
3. 判断key值否存在
判断key值是否存在可以使用以下两种方法:
方法一:
d = {'name':'xiao','age':19,'sex':'男'}
d['name'] = 'xiaoli'
if 'names' in d:
print(d['name'])
else:
print('key is not exist 01 ')
方法二:
if d.get('names'):
print(d['name'])
else:
print('key is not exist 02')
4. 删除key
d = {'name':'xiao','age':19,'sex':'男'}
d['name'] = 'xiaoli'
if d.get('name'):
d.pop('name')
else:
print('key is not exist')
print(d)
网友评论