• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

python 搞代码 4年前 (2022-01-07) 30次浏览 已收录 0个评论

这篇文章主要介绍了Python字典dict常用方法函数实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

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来源gaodaimacom搞#代%码网 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])

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持gaodaima搞代码网

以上就是Python字典dict常用方法函数实例的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python字典dict常用方法函数实例

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址