Python 字典 详解

1.创建

字典格式:键值对,一个键名对应一个值得映射关系

字典的值可以是任意数据类型,但是键必须是不可变数据类型

普通创建

>>> dic = {"name":"alex","age":20,"hobby":"girl"}     #下文中的dic都参考此处
>>> dic
{'name': 'alex', 'age': 20, 'hobby': 'girl'}

工厂函数

>>> dic1=dict((("name","alex"),("age",20)))
>>> dic1
{'name': 'alex', 'age': 20}

2.增

普通方法

>>> dic["salary"]=5000
>>> dic
{'name': 'alex', 'age': 20, 'hobby': 'girl', 'salary': 5000}

setdefault方法

>>> dic.setdefault("salary",5000)
5000
>>> dic
{'name': 'alex', 'age': 20, 'hobby': 'girl', 'salary': 5000}
>>> dic.setdefault("age",30)
20
>>> dic
{'name': 'alex', 'age': 20, 'hobby': 'girl'}

注意:此方法在字典中没有此键的时候会创建键值对,并返回值

          当字典中有此键后将不会修改原值,直接返回原值

3.查

普通方法

>>> dic["name"]
'alex'

keys方法

>>> dic.keys()
dict_keys(['name', 'age', 'hobby'])

用法:返回字典中所有键

注意:返回的类型是dict_keys类型,可以使用list等工厂函数转换类型

values方法

>>> dic.values()
dict_values(['alex', 20, 'girl'])

用法:返回字典中所有值

注意:同上

items方法

>>> dic.items()
dict_items([('name', 'alex'), ('age', 20), ('hobby', 'girl')])

用法:返回所有键值对

注意:用上

4.改

普通方法

>>> dic["age"]=18
>>> dic
{'name': 'alex', 'age': 18, 'hobby': 'girl'}

update方法

>>> dic1 = {"name":"bob","salary":5000}
>>> dic.update(dic1)
>>> dic
{'name': 'bob', 'age': 20, 'hobby': 'girl', 'salary': 5000}
>>> dic1
{'name': 'bob', 'salary': 5000}

用法:将两个字典合并,相同项覆盖原字典,不同项添加到原字典


5.删

pop方法

>>> dic.pop("name")
'alex'
>>> dic
{'age': 20, 'hobby': 'girl'}
>>>

用法:删除指定的键值对

popitem方法

>>> dic.popitem()
('hobby', 'girl')

用法:随机删除一组键值对(一般删除末尾对)

del 方法

>>> del dic["name"]
>>> dic
{'age': 20, 'hobby': 'girl'}
>>> del dic
>>> dic
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'dic' is not defined

用法:给定键的情况下删除指定的键值对,给定字典的情况下则删除整个字典

clear方法

>>> dic.clear()
>>> dic
{}

用法:清空字典

注意:虽然字典的内容被清空了,但是字典还在内存中

6.其他

fromkeys方法

>>> dic2=dict.fromkeys(["host1","host2","host3"],"test")
>>> dic2
{'host1': 'test', 'host2': 'test', 'host3': 'test'}

用法:用于初始化,键名自定后给字典中的所有键赋相同的一个值

注意:这种方法存在一些问题,最好不要使用

sorted方法

>>> sorted(dic)   #默认按照字典的键排序
['age', 'hobby', 'name']

>>> dic = {"name":"alex","age":"20","hobby":"girl"}  
>>> sorted(dic.values())
['20', 'alex', 'girl']
>>> sorted(dic.keys())
['age', 'hobby', 'name']

用法:排序

注意:当排序的内容存在不同数据类型是会报错,例如:

>>> dic
{'name': 'alex', 'age': 20, 'hobby': 'girl'}
>>> sorted(dic.values())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'int' and 'str'

字典的遍历

取键

>>> for i in dic:
	print(i)
>>>
name
age
hobby


取值

>>> for i in dic.values():
	print(i)
>>>
alex
20
girl

取键值 一 (高效方法)

>>> for i in dic:
	print(i,dic[i])
>>>
name alex
age 20
hobby girl

取键值 二

>>> for k,v in dic.items():
	print(k,v)
>>>
name alex
age 20
hobby girl




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值