您的位置:首页 > 编程语言 > Python开发

Python的字典及内置函数

2018-03-05 22:35 399 查看
python的字典是一系列键值对。{}
ex  info={'mother':'meat','father':'apple','brother':'fish','me':'water'}
访问指定键元素: print(info['mother'])
添加键值:info['aunt']='banana'
通常先建立一个空字典,在添加键值对  info{}
修改值:info['me']='wahaha'
删除键值: del info['me'] (KeyError )(访问不存在的键值。例如删除轴在访问 info['me'])
遍历字典:
遍历所有的键值:
for k,v in info.items():
print('key='+k)

print('value='+v)
print(info.items()):

dict_items([('mother', 'meat'), ('father', 'apple'), ('brother', 'fish'), ('me', 'wahaha')])

遍历所有的健:
for k in info.keys():

print('key='+k.title())
遍历所有的值
for v in info.values():
print('value='+v.title())
按顺序遍历所有的健:
for k in sorted(info.keys()):
        print(k.title())

len(info)  返回字典的键值对数
 info={'mother':50,'father':52,'brother':17,'me':23} 
ss=(str(info))   把字典转化为字符串形式

例如 print(ss[0:6])    输出“{moth"
info.clear()  删除所有的键值对,info=[]
a=info.copy()  a copy info所有的键值对
type(info )  返回<class 'dict'>

info={'mother':50,'father':52,'brother':17,'me':23}
print('uncle' in info)  返回FALSE

print('me' in info)  返回True

info.get('me'): 查看‘me’的值是多少,不存在返回NONE
print(info.get('me')) 返回23
print(info.get('uncle')) 返回None

info={'mother':50,'father':52,'brother':17,'me':23}

info.setdefault('cousin',59)    类似info.get() 但是 当cousin不存在时生产新的键值对
>>info={'mother':50,'father':52,'brother':17,'me':23,'cousin':'59'}
but info.setdefault('mother',59)  
>>>>info={'mother':50,'father':52,'brother':17,'me':23'}
info.pop('me')
info={'mother':50,'father':52,'brother':17,'me':23}
a=info.pop('me')    >>a=23
print(info)    info>>info={'mother':50,'father':52,'brother':17}

info={'mother':50,'father':52,'brother':17,'me':23}
a=info.pop('cousin')
print(a)
print(info)   报错,返回 KeyError
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: