Skip to content

Latest commit

 

History

History
396 lines (268 loc) · 7.88 KB

File metadata and controls

396 lines (268 loc) · 7.88 KB

第7节 Python字典(dict)

❤️💕💕python是一种动态的解释形语言,由于python的普遍性,学会python能更快的解决问题,以及学习其他的知识。Myblog:http://nsddd.top


[TOC]

字典

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
  • 字典用于将数据值存储在键:值对中。
  • 字典是有序、可更改且不允许重复的集合。

💡 从 Python 3.7 版开始,字典是有序的。在 Python 3.6 及更早版本中,字典是无序的。

字典是用大括号写的,并且有键和值:

创建和打印字典:

In [2]: thisdict = {
   ...:   "brand": "Ford",
   ...:   "model": "Mustang",
   ...:   "year": 1964
   ...: }
   ...: print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

字典是可变的,这意味着我们可以在字典创建后更改、添加或删除项目。

字典不允许有键相同的两个数字

In [3]: thisdict = {
   ...:   "brand": "Ford",
   ...:   "model": "Mustang",
   ...:   "year": 1964,
   ...:   "year": 2020   # 不能同时有两个year
   ...: }
   ...: print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}

字典长度一样用len()

print(len(thisdict))

获取字典键值

In [4]: thisdict
Out[4]: {'brand': 'Ford', 'model': 'Mustang', 'year': 2020}

In [5]: thisdict[year]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [5], in <cell line: 1>()
----> 1 thisdict[year]

NameError: name 'year' is not defined

In [6]: thisdict["year"]
Out[6]: 2020

In [7]: thisdict.get("year")
Out[7]: 2020

获取键

当我们不知道有多少键的时候,可以用key()方法

image-20220918151913715

In [8]: thisdict.keys()
Out[8]: dict_keys(['brand', 'model', 'year'])

获取值

In [9]: thisdict.values()

值列表是字典的视图,这意味着对字典所做的任何更改都将反映在值列表中。

获取字典

items()方法将返回字典中的每个项目,作为列表中的元组。

In [11]: thisdict.items()
Out[11]: dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 2020)])

In [12]: thisdict
Out[12]: {'brand': 'Ford', 'model': 'Mustang', 'year': 2020}

检查密钥是否存在

检查密钥是否存在

要确定字典中是否存在指定的键,请使用in关键字:

检查字典中是否存在“model”:

In [23]: thisdict = {
    ...:  "brand": "Ford",
    ...:  "model": "Mustang",
    ...:  "year": 1964
    ...: }
    ...: if "model" in thisdict:
    ...:  print("Yes, 'model' is one of the keys in the thisdict dictionary")
    ...:
Yes, 'model' is one of the keys in the thisdict dictionary

添加元素

通过添加索引来添加字典项

In [24]: thisdict = {
    ...:   "brand": "Ford",
    ...:   "model": "Mustang",
    ...:   "year": 1964
    ...: }
    ...: thisdict["color"] = "red"
    ...: print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}

更新

update()方法将使用给定参数中的项目更新字典。如果该项目不存在,则将添加该项目。

参数必须是字典,或具有键值对的可迭代对象。

In [25]: thisdict = {
    ...:   "brand": "Ford",
    ...:   "model": "Mustang",
    ...:   "year": 1964
    ...: }
    ...: thisdict.update({"color": "red"})

In [26]: thisdict
Out[26]: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}

In [27]:  thisdict.update({"color": "yellow"})

In [28]: thisdict
Out[28]: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'yellow'}

删除字典

删除字典有好几种的方式

pop方法删除具有指定键名项目

In [29]: thisdict = {
    ...:   "brand": "Ford",
    ...:   "model": "Mustang",
    ...:   "year": 1964
    ...: }
    ...: thisdict.pop("model")
    ...: print(thisdict)
{'brand': 'Ford', 'year': 1964}

popitem()方法删除最后插入的项目(在 3.7 之前的版本中,会删除随机项目):

In [30]: thisdict
Out[30]: {'brand': 'Ford', 'year': 1964}

In [31]: thisdict.popitem()
Out[31]: ('year', 1964)

In [32]: thisdict
Out[32]: {'brand': 'Ford'}

del关键字删除具有指定键名的项目,也可以删除这个字典

In [32]: thisdict
Out[32]: {'brand': 'Ford'}

In [33]: del thisdict["brand"]

In [34]: thisdict
Out[34]: {}

In [35]: del thisdict  # 没有指定键 --- 直接删除字典

遍历字典

您可以使用循环遍历字典 for

遍历字典时,返回值是字典的key,但也有返回value的方法。

In [37]: thisdict = {           # 创建字典
    ...:   "brand": "Ford",
    ...:   "model": "Mustang",
    ...:   "year": 1964,
    ...:   "name": "xiongxinwei",
    ...:   "email": "[email protected]"
    ...: }

In [38]: thisdict				# 显示字典
Out[38]:
{'brand': 'Ford',
 'model': 'Mustang',
 'year': 1964,
 'name': 'xiongxinwei',
 'email': '[email protected]'}

In [39]: type(thisdict)
Out[39]: dict

In [40]: for x in thisdict:		# 遍历字典的所有key
    ...:     print(x)
    ...:
brand
model
year
name
email

In [41]: for x in thisdict:		# 遍历字典的所有value
    ...:     print(thisdict[x])
    ...:
Ford
Mustang
1964
xiongxinwei
xxw@nsddd.top

复制字典

In [43]: thisdict
Out[43]:
{'brand': 'Ford',
 'model': 'Mustang',
 'year': 1964,
 'name': 'xiongxinwei',
 'email': '[email protected]'}

In [44]: thisdict2 = thisdict.copy()

In [45]: thisdict2
Out[45]:
{'brand': 'Ford',
 'model': 'Mustang',
 'year': 1964,
 'name': 'xiongxinwei',
 'email': '[email protected]'}

也可以使用第二种方法:

mydict = dict(thisdict)

嵌套字典

嵌套字典对我们来说还是比较重要的,因为嵌套字典可以解决我们很多的麻花

In [52]: myfamily = {
    ...:   "child1" : {
    ...:     "name" : "Emil",
    ...:     "year" : 2004
    ...:   },
    ...:   "child2" : {
    ...:     "name" : "Tobias",
    ...:     "year" : 2007
    ...:   },
    ...:   "child3" : {
    ...:     "name" : "Linus",
    ...:     "year" : 2011
    ...:   }
    ...: }

In [53]: myfamily
Out[53]:
{'child1': {'name': 'Emil', 'year': 2004},
 'child2': {'name': 'Tobias', 'year': 2007},
 'child3': {'name': 'Linus', 'year': 2011}}

In [54]: myfamily["child1"]
Out[54]: {'name': 'Emil', 'year': 2004}

或者你创建三个字典,然后创建一个包含其他三个字典的字典:

In [56]: child1 = {
    ...:   "name" : "Emil",
    ...:   "year" : 2004
    ...: }
    ...: child2 = {
    ...:   "name" : "Tobias",
    ...:   "year" : 2007
    ...: }
    ...: child3 = {
    ...:   "name" : "Linus",
    ...:   "year" : 2011
    ...: }
    ...:
    ...: myfamily = {
    ...:   "child1" : child1,
    ...:   "child2" : child2,
    ...:   "child3" : child3
    ...: }

In [57]: myfamily
Out[57]:
{'child1': {'name': 'Emil', 'year': 2004},
 'child2': {'name': 'Tobias', 'year': 2007},
 'child3': {'name': 'Linus', 'year': 2011}}

END 链接