欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python字典dict常用方法函数实例

时间:2021-04-29 10:55:37|栏目:Python代码|点击:

dict={'name':'Joe','age':18,'height':60}

clear,清空

dict.clear()
#运行结果{}

pop,移除指定key的键值对并返回vlaue(如果没有该key,可返回指定值),popitem,默认移除最后一个键值对

print(dict.pop('age'))
print(dict)
#结果18,{'name': 'Joe', 'height': 60}
print(dict.pop('agea','erro'))
print(dict)
#结果erro,{'name': 'Joe', 'age': 18, 'height': 60}
print(dict.popitem())
print(dict)
#结果('height', 60),{'name': 'Joe', 'age': 18}

del,删除字典的另一种方式

del dict['age']
print(dict)
#结果{'name': 'Joe', 'height': 60}

get,返回指定键的值,如果值不在字典中返回default值,等同于dict.__getitem__('name')

print(dict.get('name'))
#结果Joe
print(dict.get('hobby'))
#结果None
print(dict.get('hobby','basketball'))
#结果basketball

setdefault,和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default

print(dict.setdefault('hobby'))
print(dict)
#结果None,{'name': 'Joe', 'age': 18, 'height': 60, 'hobby': None}
print(dict.setdefault('hobby','basketball'))
print(dict)
#结果basketball,{'name': 'Joe', 'age': 18, 'height': 60, 'hobby': 'basketball'}

update,更新字典,有key则更新该key对应的vlaue,没有则新增

dict.update({'age':20})
print(dict)
#结果{'name': 'Joe', 'age': 20, 'height': 60}
dict.update({'hobby':'run'})
print(dict)
#结果{'name': 'Joe', 'age': 18, 'height': 60, 'hobby': 'run'}

fromkeys,创建新字典,以seq为key,vlaue为字典的初始值

seq = ('a', 'b', 'c')
print(dict.fromkeys(seq))
#结果{'a': None, 'b': None, 'c': None}
print(dict.fromkeys(seq,'oh'))
#结果{'a': 'oh', 'b': 'oh', 'c': 'oh'}

字典的打印,取值等

print(dict.items())
print(dict.values())
print(dict.keys())
#结果
dict_items([('name', 'Joe'), ('age', 18), ('height', 60)])
dict_values(['Joe', 18, 60])
dict_keys(['name', 'age', 'height'])

字典的遍历,遍历key

for i in dict:
print(i)
#结果
name
age
height
#相同效果的遍历如下:
for key in dict.keys():
print(key)
#
字典的遍历,遍历value
for vlaue in dict.values():
print(vlaue)
#结果
Joe
18
60

字典的遍历,遍历item

#10.1输出为元组的方式
for item in dict.items():
print(item)
#结果
('name', 'Joe')
('age', 18)
('height', 60)
#10.2输出为字符串的方式
for key,vlaue in dict.items():
print(key,vlaue)
#结果
name Joe
age 18
height 60
#输出为字符串的另一种方式
for i in dict:
print(i,dict[i])

上一篇:Python实现Dijkstra算法

栏    目:Python代码

下一篇:简单了解Django应用app及分布式路由

本文标题:Python字典dict常用方法函数实例

本文地址:http://www.codeinn.net/misctech/110950.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有