目录
目标
版本
官方文档
简介
实战
创建
循环
常用方法
掌握字典类型的使用方法,包括:创建、循环、常用方法等操作。
Python 3.12.0
Mapping Types — dicthttps://docs.python.org/3/library/stdtypes.html#mapping-types-dict
官方定义
Mapping Types — dict
A mapping object maps hashable values to arbitrary objects. Mappings are mutable objects. There is currently only one standard mapping type, the dictionary. (For other containers see the built-in list, set, and tuple classes, and the collections module.)
A dictionary’s keys are almost arbitrary values. Values that are not hashable, that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys. Values that compare equal (such as
1
,1.0
, andTrue
) can be used interchangeably to index the same dictionary entry.
译文
Python中仅有一种标准的映射类型,即字典(dictionary)类型。
不可变数据类型才可以作为字典的键(key)。比如:
分析
字典数据类型是键值对的形式,这与java中的HashMap很相似。
官方定义
Dictionaries can be created by several means:
Use a comma-separated list of
key: value
pairs within braces:{'jack': 4098, 'sjoerd': 4127}
or{4098: 'jack', 4127: 'sjoerd'}
Use a dict comprehension:
{}
,{x: x ** 2 for x in range(10)}
Use the type constructor:
dict()
,dict([('foo', 100), ('bar', 200)])
,dict(foo=100, bar=200)
这里给出了字典的三种创建方法:
方法一(用大括号创建)
myDict={"name":"zhangsan","age":12,"sex":1,False:"yes",True:"no",frozenset(["a","b","c"]):"Hello World."}
#输出:{'name': 'zhangsan', 'age': 12, 'sex': 1, False: 'yes', True: 'no', frozenset({'a', 'b', 'c'}): 'Hello World.'}
print(myDict)
方法二(用字典推导式创建)
fruitList = ['apple', 'banana', 'orange', 'kiwi', 'grape']
#水果名称作key,水果单词长度作value
fruitDict={key:len(key) for key in fruitList}
#输出:{'name': 'zhangsan', 'age': 12, 'sex': 1, False: 'yes', True: 'no', frozenset({'a', 'b', 'c'}): 'Hello World.'}
print(fruitDict)
方法三(用构造方法创建)
用关键字作key创建字典
myDict=dict(name="Tom",age=12,sex=1)
#输出:{'name': 'Tom', 'age': 12, 'sex': 1}
print(myDict)
用可迭代对象创建字典
myDict=dict([("name","Tom"),("age",12),("sex",1)])
#输出:{'name': 'Tom', 'age': 12, 'sex': 1}
print(myDict)
混合模式创建
myDict=dict([("name","Tom"),("age",12)],sex=1)
#输出:{'name': 'Tom', 'age': 12, 'sex': 1}
print(myDict)
遍历字典的key
#方法一
myDict=dict(name="Tom",age=12,sex=1)
#输出:name age sex
for key in myDict:
print(key,end=" ")
#方法二
myDict=dict(name="Tom",age=12,sex=1)
#输出:name age sex
for key in iter(myDict):
print(key,end=" ")
#方法三
myDict=dict(name="Tom",age=12,sex=1)
#输出:name age sex
for key in myDict.keys():
print(key,end=" ")
反向遍历字典中的key
myDict={"name":"Tom","age":12,"sex":1}
#输出:sex age name
for key in reversed(myDict):
print(key,end=" ")
遍历字典的value
myDict=dict(name="Tom",age=12,sex=1)
#输出:Tom 12 1
for value in myDict.values():
print(value,end=" ")
遍历字典的键值对
myDict=dict(name="Tom",age=12,sex=1)
"""
输出:
name = Tom
age = 12
sex = 1
"""
for key, value in myDict.items():
print(key,"=",value)
使用视图对象循环
myDict=dict(name="Tom",age=12,sex=1)
#输出:dict_items([('name', 'Tom'), ('age', 12), ('sex', 1)])
#dict_items是字典视图对象的类型
print(myDict.items(),type(myDict.items()))
"""
输出:
('name', 'Tom')
('age', 12)
('sex', 1)
"""
for item in myDict.items():
print(item,type(item))
以集合的形式获取字典的所有key
myDict={"name":"Tom","age":12,"sex":1}
keyList=list(myDict)
#输出:['name', 'age', 'sex']
print(keyList,type(keyList))
获取键值对数量
myDict={"name":"Tom","age":12,"sex":1}
dictLen=len(myDict)
#输出:3
print(dictLen,type(dictLen))
根据key获取value
class MyDict(dict):
def __missing__(self, key):
return "{}不存在".format(key)
#用字典的字类MyDict的构造方法创建字典
yourDict=MyDict(name="Tom",age=12,sex=1)
#输出:
print(type(yourDict))
#输出:Tom
print(yourDict["name"])
#输出:birthday不存在
print(yourDict["birthday"])
根据key设置value
myDict={"name":"Tom","age":12,"sex":1}
myDict["name"]="Green"
#输出:{'name': 'Green', 'age': 12, 'sex': 1}
print(myDict)
根据key删除元素
myDict={"name":"Tom","age":12,"sex":1}
del myDict["name"]
#输出:{'age': 12, 'sex': 1}
print(myDict)
根据key删除元素并返回value
myDict={"name":"Tom","age":12,"sex":1}
name=myDict.pop("name");
#输出:Tom
print(name)
birthday=myDict.pop("birthday","没有这个key");
#输出:没有这个key
print(birthday)
birthday=myDict.pop("birthday");
#报错
print(birthday)
是否包含某个key
myDict={"name":"Tom","age":12,"sex":1}
#输出:True
print("name" in myDict)
是否不包含某个key
myDict={"name":"Tom","age":12,"sex":1}
#输出:True
print("name" not in myDict)
清空字典
myDict={"name":"Tom","age":12,"sex":1}
myDict.clear()
#输出:{}
print(myDict)
拷贝字典(浅拷贝)
myDict={"name":"Tom","age":12,"sex":1}
yourDict=myDict.copy()
#输出:不同的id
print(id(yourDict),id(myDict))
#输出:相同的id
print(id(yourDict.get("name")),id(myDict.get("name")))
移除并返回字典中的一个元素,返回对象是元组类型。
从Python3.7版本开始,popitem方法按照后进先出,之前的版本随机返回。
myDict={"name":"Tom","age":12,"sex":1}
oneTuple=myDict.popitem()
#输出:('sex', 1)
print(oneTuple,type(oneTuple))
twoTuple=myDict.popitem()
#输出:('age', 12)
print(twoTuple,type(twoTuple))
threeTuple=myDict.popitem()
#输出:('name', 'Tom')
print(threeTuple,type(threeTuple))
print(myDict)
fourTuple=myDict.popitem()
#报错,因为此时myDict里没有元素了。
print(fourTuple,type(fourTuple))
如果字典中没有这个key则往字典插入数据,如果字典中有这个key,则不修改数据。默认值是可选参数,默认为None。
myDict={"name":"Tom","age":12,"sex":1}
myDict.setdefault("name","Jack")
#输出:{'name': 'Tom', 'age': 12, 'sex': 1}
print(myDict)
myDict.setdefault("birthday","1999-09-09")
#输出:{'name': 'Tom', 'age': 12, 'sex': 1, 'birthday': '1999-09-09'}
print(myDict)
myDict.setdefault("occupation")
#输出:{'name': 'Tom', 'age': 12, 'sex': 1, 'birthday': '1999-09-09', 'occupation': None}
print(myDict)
myDict.setdefault("name")
#输出:{'name': 'Tom', 'age': 12, 'sex': 1, 'birthday': '1999-09-09', 'occupation': None}
print(myDict)
批量更新数据
#根据字典修改数据
myDict={"name":"Tom","age":12,"sex":1}
yourDict={"name":"Jack","age":20,"birthday":"1999-09-09"}
myDict.update(yourDict)
#输出:{'name': 'Jack', 'age': 20, 'sex': 1, 'birthday': '1999-09-09'}
print(myDict)
#根据关键词修改数据
myDict.update(name="Jack",age=20,birthday="1990-09-09")
#输出:{'name': 'Jack', 'age': 20, 'sex': 1, 'birthday': '1990-09-09'}
print(myDict)
#根据迭代对象修改数据
myList=[("work","farmer"),("name","Green")]
myDict.update(myList)
#输出:{'name': 'Green', 'age': 20, 'sex': 1, 'birthday': '1999-09-09', 'work': 'farmer'}
print(myDict)
根据优先级合并两个字典产生新字典
Python3.9版本中引入的字典合并操作符。
#根据字典修改数据
myDict={"name":"Tom","age":12,"sex":1}
yourDict={"name":"Jack","age":20,"birthday":"1999-09-09","sex":None}
otherDict=myDict | yourDict
#输出:
print(type(otherDict))
#输出:{'name': 'Jack', 'age': 20, 'sex': 1, 'birthday': '1999-09-09'}
#分析:yourDict在右边,所以如果key相同,取yourDict的value
print(otherDict)
根据优先级修改两个字典产生新字典
Python3.9版本中引入的字典合并操作符。
#根据字典修改数据
myDict={"name":"Tom","age":12,"sex":1}
yourDict={"name":"Jack","age":20,"birthday":"1999-09-09","sex":None}
myDict |= yourDict
#输出:
print(type(myDict))
#输出:{'name': 'Jack', 'age': 20, 'sex': None, 'birthday': '1999-09-09'}
#分析:yourDict在右边,所以如果key相同,取yourDict的value
print(myDict)