专业编程基础技术教程

网站首页 > 基础教程 正文

python中的字典是什么?(python中字典的操作方法)

ccvgpt 2024-07-18 12:51:58 基础教程 8 ℃

“一起学习,一起成长!”

字典(dictionary)与列表类似,但其中元素的顺序无关紧要,因为它们不是通过像0或1的偏移量访问的。取而代之,每个元素拥有与之对应的互不相同的键(key),通过键来访问。键通常是字符串,但它还可以是Python中其他任意的不可变类型:布尔型、整型、浮点型、元组、字符串,以及其他一些在后面的内容会见到的类型。字典是可变的,因此你可以增加、删除或修改其中的键值对。

python中的字典是什么?(python中字典的操作方法)

1. 使用{}创建字典

>>> empty_dict={}

>>> empty_dict

{}

>>> bierce={"day":"mostly misspent","positive":"one's voice","misfortune":"never misses"}

>>> bierce

{'day': 'mostly misspent', 'positive': "one's voice", 'misfortune': 'never misses'}

2. 使用dict()转换为字典

可以用dict()将包含双值子序列的序列转换成字典。

每个子序列的第一个元素作为键,第二个元素作为值。

>>> lol=[['a','b'],['c','d'],['e','f']]

>>> dict(lol)

{'a': 'b', 'c': 'd', 'e': 'f'}

可以对任何包含双值子序列的序列使用dict():

包含双值元组的列表:

>>> lot=[('a','b'),('b','d'),('e','f')]

>>> lot

[('a', 'b'), ('b', 'd'), ('e', 'f')]

>>> dict(lot)

{'a': 'b', 'b': 'd', 'e': 'f'}

包含双值列表的元组:

>>> tol=(['a','b'],['c','d'],['e','f'])

>>> dict(tol)

{'a': 'b', 'c': 'd', 'e': 'f'}

双字符的字符串组成的列表:

>>> los=['ab','cd','ef']

>>> dict(los)

{'a': 'b', 'c': 'd', 'e': 'f'}

双字符的字符串组成的元组:

>>> tos=('ab','cd','ef')

>>> dict(tos)

{'a': 'b', 'c': 'd', 'e': 'f'}

3. 使用[key]添加或修改元素

>>> python={}

>>> python={'a':'b','c':'d','e':'f','g':'h'}

>>> python

{'a': 'b', 'c': 'd', 'e': 'f', 'g': 'h'}

添加新键值对:

>>> python['new1']='new2'

>>> python

{'a': 'b', 'c': 'd', 'e': 'f', 'g': 'h', 'new1': 'new2'}

使用键修改值:

>>> python['new1']='new2-1'

>>> python

{'a': 'b', 'c': 'd', 'e': 'f', 'g': 'h', 'new1': 'new2-1'}

字典的键必须保证互不相同。如果创建字典时同一个键出现了两次,那么后面出现的值会取代之前的值:

>>> pythoon={'a':'b','a':'c','c':'d'}

>>> pythoon

{'a': 'c', 'c': 'd'}

4. 使用update()合并字典

使用update()可以将一个字典的键值对复制到另一个字典中去。

>>> python={'a':'b','c':'d','e':'f'}

>>> others={'age':26,'pay':'1236'}

>>> python.update(others)

>>> python

{'a': 'b', 'c': 'd', 'e': 'f', 'age': 26, 'pay': '1236'}

如果待添加的字典与待扩充的字典包含同样的键会怎么样?新归入字典的值会取代原有的值:

>>> python2={'age':89}

>>> python.update(python2)

>>> python

{'a': 'b', 'c': 'd', 'e': 'f', 'age': 89, 'pay': '1236'}

5. 使用del删除具有指定键的元素

>>> del python['age']

>>> python

{'a': 'b', 'c': 'd', 'e': 'f', 'pay': '1236'}

>>> del python['a']

>>> python

{'c': 'd', 'e': 'f', 'pay': '1236'}

6. 使用clear()删除所有元素

使用clear(),或者给字典变量重新赋值一个空字典({})可以将字典中所有元素删除:

>>> python.clear()

>>> python

{}

>>> python={}

>>> python

7. 使用in判断是否存在

如果希望判断某一个键是否存在于一个字典中,可以使用in。

>>> python={'a':'b','c':'d','e':'f'}

>>> 'a' in python

True

>>> 'f' in python

False

8. 使用[key]获取元素

这是对字典最常进行的操作,只需指定字典名和键即可获得对应的值:

>>> python['a']

'b'

如果字典中不包含指定的键,会产生一个异常:

>>> python['f']

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

KeyError: 'f'

有两种方法可以避免这种情况的发生。第一种是在访问前通过in测试键是否存在:

>>> 'f' in python

False

另一种方法是使用字典函数get():

>>> python.get('a')

'b'

反之,若键不存在,如果指定了可选值,那么get()函数将返回这个可选值:

>>> python.get('f','not in python')

'not in python'

否则,会得到None(在交互式解释器中什么也不会显示):

>>> python.get('f',None)

>>>

9. 使用keys()获取所有键

使用keys()可以获得字典中的所有键。

>>> python.keys()

dict_keys(['a', 'c', 'e'])

但在python3中,你只能自己调用list()将dict_keys转换为列表类型。

>>> list(python.keys())

['a', 'c', 'e']

在python3里,同样需要手动使用list()将values()和items()返回值转换为普通的python列表。

10. 使用values获取所有值

使用values()可以获取字典中的所有值:

>>> list(python.values())

['b', 'd', 'f']

11. 使用items()获取所有键值对

使用items()函数可以获取字典中所有的键值对:

>>> list(python.items())

[('a', 'b'), ('c', 'd'), ('e', 'f')]

12.诚邀扫描下方二维码关注公众号,一起学习,一起成长! 使用=赋值,使用copy()复制

与列表一样,对字典内容进行的修改会反映到所有与之相关联的变量名上:

>>> python={'a':'b','c':'d','e':'f'}

>>> python_new=python

>>> python_new

{'a': 'b', 'c': 'd', 'e': 'f'}

>>> python['a']='g'

>>> python

{'a': 'g', 'c': 'd', 'e': 'f'}

若想避免这种情况,可以使用copy()将字典复制到一个新的字典中:

>>> python_new1=python.copy()

>>> python_new1

{'a': 'g', 'c': 'd', 'e': 'f'}

>>> python_new1['a']='u'

>>> python_new1

{'a': 'u', 'c': 'd', 'e': 'f'}

「亲,如果笔记对您有帮助,收藏的同时,记得给点个赞、加个关注哦!感谢!」

「诚邀关注公众号“issnail”,会有惊喜哦!感谢!」

「文中代码均亲测过,若有错误之处,欢迎批评指正,一起学习,一起成长!」

参考书目:python语言及其应用

Tags:

最近发表
标签列表