Python dict 字典方法

该篇仅作为个人笔记,欢迎收藏。
注意:字典中的元素没有顺序之说。
假如我们有一个字典对象:

dict1 = {"name": "Xiao Ming", "age": 18, "gender": "male", "status": "single"}

len()方法:获取字典对象中的元素个数。

dict1 = {"name": "Xiao Ming", "age": 18, "gender": "male", "status": "single"}
print(len(dict1))
"""
result:
4
"""

dict.[key]方法:通过某个key值(键值)获取与其对应的某个value值(值)

dict1 = {"name": "Xiao Ming", "age": 18, "gender": "male", "status": "single"}
print(dict1["name"])
"""
result:
Xiao Ming
"""

dict.[key] = "xxx"方法:1.当指定的条目字典中不存在时,直接向字典中添加新条目,不用去更新字典,2.当指定的条目字典中存在时,修改字典中的值
举例1

dict1 = {"name": "Xiao Ming", "age": 18, "gender": "male", "status": "single"}
print(dict1)
dict1["city"] = "Xi'an"
print(dict1)
"""
result:
{'name': 'Xiao Ming', 'age': 18, 'gender': 'male', 'status': 'single'}
{'name': 'Xiao Ming', 'age': 18, 'gender': 'male', 'status': 'single', 'city': "Xi'an"}
"""

举例2

dict1 = {"name": "Xiao Ming", "age": 18, "gender": "male", "status": "single"}
dict1["age"] = 26
print(dict1)
"""
result:
{'name': 'Xiao Ming', 'age': 26, 'gender': 'male', 'status': 'single'}
"""

updata()方法:将字典dict2中的元素添加到字典dict1

dict1 = {"name": "Xiao Ming", "age": 18, "gender": "male", "status": "single"}
dict2 = {"pet": "cat"}
dict1.update(dict2)
print(dict1)
"""
result:
{'name': 'Xiao Ming', 'age': 18, 'gender': 'male', 'status': 'single', 'pet': 'cat'}
"""

del dict[key]方法:删除字典中对应key值的value值,注意与列表的del()方法(超链接点击跳转)做区分。

dict1 = {"name": "Xiao Ming", "age": 18, "gender": "male", "status": "single"}
del dict1["name"]
print(dict1)
"""
result:
{'age': 18, 'gender': 'male', 'status': 'single'}
"""

pop()方法:删除字典中对一个key值的value

dict1 = {"name": "Xiao Ming", "age": 18, "gender": "male", "status": "single"}
dict1.pop("name")
print(dict1)
"""
result:
{'age': 18, 'gender': 'male', 'status': 'single'}
"""

clear()方法:删除字典中的所有条目

dict1 = {"name": "Xiao Ming", "age": 18, "gender": "male", "status": "single"}
dict1.clear()
print(dict1)
"""
result:
{}
"""

items()方法:返回键值对tuple的列表

dict1 = {"name": "Xiao Ming", "age": 18, "gender": "male", "status": "single"}
print(dict1.items())
"""
result:
dict_items([('name', 'Xiao Ming'), ('age', 18), ('gender', 'male'), ('status', 'single')])
"""

keys()方法:返回键的列表

dict1 = {"name": "Xiao Ming", "age": 18, "gender": "male", "status": "single"}
print(dict1.keys())
"""
result:
dict_keys(['name', 'age', 'gender', 'status'])
"""

values()方法:返回值的列表

dict1 = {"name": "Xiao Ming", "age": 18, "gender": "male", "status": "single"}
print(dict1.values())
"""
result:
dict_values(['Xiao Ming', 18, 'male', 'single'])
"""

key in dict方法:判断字典中的某个键值是否存在。

dict1 = {"name": "Xiao Ming", "age": 18, "gender": "male", "status": "single"}
print("age" in dict1)
"""
result:
True
"""

dict.get(key)方法:判断字典中的某个键值是否存在,存在,则返回键值,若没有则返回None

dict1 = {"name": "Xiao Ming", "age": 18, "gender": "male", "status": "single"}
print(dict1.get("age"))
print(dict1.get("income"))
"""
result:
18
None
"""

dcit.get(key)方法的好处,在不确定字典中是否存在对于的键值时,如果直接使用dict[key]会产生错误导致程序中断,而使用dict.get(key)可以保证程序不中断,继续执行。请看如下代码:

dict1 = {"name": "Xiao Ming", "age": 18, "gender": "male", "status": "single"}
print(dict1["xiao xiao"]) 
"""
result:
Traceback (most recent call last):
  File "C:/Users/15025/Desktop/Intelligence/debug00.py", line 14, in <module>
    print(dict1["income"])
KeyError: 'income'
"""

dict.get()方法也可以指定当选取对象不存在时的返回值(之前提到默认不存在返回为None)。比如:

dict1 = {"name": "Xiao Ming", "age": 18, "gender": "male", "status": "single"}
print(dict1.get("income", False))
"""
result:
False
"""

可以看到此时的返回值变为了False
事实上,我们也可以通过直接使用dict.get(key)来得到类似的结果,但是在使用之前我们需要做一下设定。

dict1 = {"name": "Xiao Ming", "age": 18, "gender": "male", "status": "single"}
dict1.setdefault("xiao xiao", False)
print(dict1["xiao xiao"])
"""
result:
False
"""

可以看到此时程序也没有报错,而是返回了我们设定的结果。
举例3:从列表中快速创建集合,并统计列表中对应元素出现的次数。

list1 = ["a", "v", "c", "d", "a"]
c = {}
for i in set(list1):
    c[i] = list1.count(i)

print(c)
"""
result:
{'d': 1, 'c': 1, 'v': 1, 'a': 2}
"""

码字不易,如果大家觉得有用,请高抬贵手给一个赞让我上推荐让更多的人看到吧~

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

勤奋的大熊猫

你的鼓励将是我写作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值