搜尋
首頁後端開發Python教學python字典的常用操作方法小结

Python字典是另一种可变容器模型(无序),且可存储任意类型对象,如字符串、数字、元组等其他容器模型。本文章主要介绍Python中字典(Dict)的详解操作方法,包含创建、访问、删除、其它操作等,需要的朋友可以参考下。

字典由键和对应值成对组成。字典也被称作关联数组或哈希表。基本语法如下:

1.创建字典

>>> dict = {'ob1':'computer', 'ob2':'mouse', 'ob3':'printer'}
技巧:
字典中包含列表:dict={'yangrong':['23','IT'],"xiaohei":['22','dota']}
字典中包含字典:dict={'yangrong':{"age":"23","job":"IT"},"xiaohei":{"'age':'22','job':'dota'"}}
注意:
每个键与值用冒号隔开(:),每对用逗号,每对用逗号分割,整体放在花括号中({})。
键必须独一无二,但值则不必。

2.访问字典里的值

>>> dict = {'ob1':'computer', 'ob2':'mouse', 'ob3':'printer'}
>>> print(dict['ob1'])
computer
如果用字典里没有的键访问数据,会输出错误如下:
>>> print(dict['ob4'])
Traceback (most recent call last):
 File "<pyshell#110>", line 1, in <module>
  print(dict['ob4'])

访问所有值
>>> dict1 = {'ob1':'computer', 'ob2':'mouse', 'ob3':'printer'}
>>> for key in dict1:
  print(key,dict1[key])  
ob3 printer
ob2 mouse
ob1 computer

3.修改字典

>>> dict = {'ob1':'computer', 'ob2':'mouse', 'ob3':'printer'}
>>> dict['ob1']='book'
>>> print(dict)
{'ob3': 'printer', 'ob2': 'mouse', 'ob1': 'book'}

4.删除字典

能删单一的元素
>>> dict = {'ob1':'computer', 'ob2':'mouse', 'ob3':'printer'}
>>> del dict['ob1']
>>> print(dict)
{'ob3': 'printer', 'ob2': 'mouse'}

删除字典中所有元素 
>>> dict1={'ob1':'computer','ob2':'mouse','ob1':'printer'}
>>> dict1.clear()
>>> print(dict1)
{}


删除整个字典,删除后访问字典会抛出异常。
>>> dict1 = {'ob1':'computer', 'ob2':'mouse', 'ob3':'printer'}
>>> del dict1
>>> print(dict1)
Traceback (most recent call last):
 File "<pyshell#121>", line 1, in <module>
  print(dict1)
NameError: name 'dict1' is not defined

5.更新字典

update()方法可以用来将一个字典的内容添加到另外一个字典中:
>>> dict1 = {'ob1':'computer', 'ob2':'mouse'}
>>> dict2={'ob3':'printer'}
>>> dict1.update(dict2)
>>> print(dict1)
{'ob3': 'printer', 'ob2': 'mouse', 'ob1': 'computer'}

6.映射类型相关的函数

>>> dict(x=1, y=2) 
{'y': 2, 'x': 1} 
>>> dict8 = dict(x=1, y=2) 
>>> dict8 
{'y': 2, 'x': 1} 
>>> dict9 = dict(**dict8) 
>>> dict9 
{'y': 2, 'x': 1} 
 
dict9 = dict8.copy()

7.字典键的特性

字典值可以没有限制地取任何python对象,既可以是标准的对象,也可以是用户定义的,但键不行。
两个重要的点需要记住:
1)不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住  
>>> dict1={'ob1':'computer','ob2':'mouse','ob1':'printer'}
>>> print(dict1)
{'ob2': 'mouse', 'ob1': 'printer'}
  
2)键必须不可变,所以可以用数,字符串或元组充当,用列表就不行
>>> dict1 = {['ob1']:'computer', 'ob2':'mouse', 'ob3':'printer'}
Traceback (most recent call last):
 File "<pyshell#125>", line 1, in <module>
  dict1 = {['ob1']:'computer', 'ob2':'mouse', 'ob3':'printer'}
TypeError: unhashable type: 'list'

8.字典内置函数&方法

Python字典包含了以下内置函数:
1、cmp(dict1, dict2):比较两个字典元素。(python3后不可用)
2、len(dict):计算字典元素个数,即键的总数。
3、str(dict):输出字典可打印的字符串。
4、type(variable):返回输入的变量类型,如果变量是字典就返回字典类型。

Python字典包含了以下内置方法:
1、radiansdict.clear():删除字典内所有元素
2、radiansdict.copy():返回一个字典的浅复制
3、radiansdict.fromkeys():创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
4、radiansdict.get(key, default=None):返回指定键的值,如果值不在字典中返回default值
5、radiansdict.has_key(key):如果键在字典dict里返回true,否则返回false
6、radiansdict.items():以列表返回可遍历的(键, 值) 元组数组
7、radiansdict.keys():以列表返回一个字典所有的键
8、radiansdict.setdefault(key, default=None):和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default
9、radiansdict.update(dict2):把字典dict2的键/值对更新到dict里
10、radiansdict.values():以列表返回字典中的所有值

以上这篇python字典的常用操作方法小结就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python:深入研究彙編和解釋Python:深入研究彙編和解釋May 12, 2025 am 12:14 AM

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

Python是一種解釋或編譯語言,為什麼重要?Python是一種解釋或編譯語言,為什麼重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

對於python中的循環時循環與循環:解釋了關鍵差異對於python中的循環時循環與循環:解釋了關鍵差異May 12, 2025 am 12:08 AM

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

循環時:實用指南循環時:實用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

Python:它是真正的解釋嗎?揭穿神話Python:它是真正的解釋嗎?揭穿神話May 12, 2025 am 12:05 AM

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

與同一元素的Python串聯列表與同一元素的Python串聯列表May 11, 2025 am 12:08 AM

concatenateListSinpythonWithTheSamelements,使用:1)operatoTotakeEpduplicates,2)asettoremavelemavphicates,or3)listcompreanspherensionforcontroloverduplicates,每個methodhasdhasdifferentperferentperferentperforentperforentperforentperfornceandordorimplications。

解釋與編譯語言:Python的位置解釋與編譯語言:Python的位置May 11, 2025 am 12:07 AM

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允許ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

循環時:您什麼時候在Python中使用?循環時:您什麼時候在Python中使用?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具