目标
版本
官方文档
Mapping Types — dicthttps://docs.python.org/3/library/stdtypes.html#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)类型。
字典数据类型是键值对的形式,这与java中的HashMap很相似。
实战
创建
官方定义
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)
方法三(用构造方法创建)
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)
循环
#方法一
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=" ")
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)]) <class 'dict_items'>
#dict_items是字典视图对象的类型
print(myDict.items(),type(myDict.items()))
"""
输出:
('name', 'Tom') <class 'tuple'>
('age', 12) <class 'tuple'>
('sex', 1) <class 'tuple'>
"""
for item in myDict.items():
print(item,type(item))
常用方法
myDict={"name":"Tom","age":12,"sex":1}
keyList=list(myDict)
#输出:['name', 'age', 'sex'] <class 'list'>
print(keyList,type(keyList))
myDict={"name":"Tom","age":12,"sex":1}
dictLen=len(myDict)
#输出:3 <class 'int'>
print(dictLen,type(dictLen))
class MyDict(dict):
def __missing__(self, key):
return "{}不存在".format(key)
#用字典的字类MyDict的构造方法创建字典
yourDict=MyDict(name="Tom",age=12,sex=1)
#输出:<class '__main__.MyDict'>
print(type(yourDict))
#输出:Tom
print(yourDict["name"])
#输出:birthday不存在
print(yourDict["birthday"])
myDict={"name":"Tom","age":12,"sex":1}
myDict["name"]="Green"
#输出:{'name': 'Green', 'age': 12, 'sex': 1}
print(myDict)
myDict={"name":"Tom","age":12,"sex":1}
del myDict["name"]
#输出:{'age': 12, 'sex': 1}
print(myDict)
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) <class 'tuple'>
print(oneTuple,type(oneTuple))
twoTuple=myDict.popitem()
#输出:('age', 12) <class 'tuple'>
print(twoTuple,type(twoTuple))
threeTuple=myDict.popitem()
#输出:('name', 'Tom') <class 'tuple'>
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)
#根据字典修改数据
myDict={"name":"Tom","age":12,"sex":1}
yourDict={"name":"Jack","age":20,"birthday":"1999-09-09","sex":None}
otherDict=myDict | yourDict
#输出:<class 'dict'>
print(type(otherDict))
#输出:{'name': 'Jack', 'age': 20, 'sex': 1, 'birthday': '1999-09-09'}
#分析:yourDict在右边,所以如果key相同,取yourDict的value
print(otherDict)
#根据字典修改数据
myDict={"name":"Tom","age":12,"sex":1}
yourDict={"name":"Jack","age":20,"birthday":"1999-09-09","sex":None}
myDict |= yourDict
#输出:<class 'dict'>
print(type(myDict))
#输出:{'name': 'Jack', 'age': 20, 'sex': None, 'birthday': '1999-09-09'}
#分析:yourDict在右边,所以如果key相同,取yourDict的value
print(myDict)
原文地址:https://blog.csdn.net/qq_39706570/article/details/134654258
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_5919.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!