Dictionary is a commonly used data structure provided by Python, which is used to store data with mapping relationships. It is a mutable container model and can store any type of object. A dictionary is an unordered, mutable, and indexed collection. In Python, a dictionary is written with curly braces {} and consists of key-value pairs, namely key and value. Each key-value pair in the dictionary is separated by colon : and each key-value pair is separated by comma , . The keys in the dictionary are unique. If the key is repeated, the value corresponding to the subsequent key will replace the value corresponding to the previous key. The value can be any data type, but the key must be immutable, such as string, number or Tuples can be used as dictionary keys, but lists cannot be used as key values. eg:
dict1 = {"name":"张三","age":18,"地址":"China"} dict2 = {"a":1,"b":2,"c":1,"d":3} dict3 = {1:"a",2:"b",3:"c"} dict4 = {}表示创建一个空的字典
1. Accessing values in the dictionary
Accessing the dictionary in python is to access the values in the dictionary through keys. If you access data with keys that are not in the dictionary, an error will be output.
eg:
dict1 = {"name":"张三","age":18,"地址":"China"} m = dict1["name"] print(m)
At this time, the printed result is "Zhang San", which means that the access dictionary key is the value corresponding to "name".
2. Access all keys in the dictionary Or all values
eg:
dict1 = {"name":"张三","age":18,"地址":"China"} m = dict1.keys() n = dict1.values() print(m) print(n)
At this time, the printed result is m for dict_keys(['name', 'age', 'address']), which obtains all the values in the dictionary dict1 The value of the key. n is dict_values(['Zhang San', 18, 'China']), which obtains all the value values in the dictionary dict1.
3. Modify the dictionary
Add a new key pair value in the dictionary, or modify the value corresponding to an existing key
Add a new key pair value:
dict1 = {"name":"张三","age":18,"地址":"China"} dict1["成绩"]="优秀" print(dict1)
The printed result at this time is {'name': 'Zhang San', 'age': 18, 'Address': 'China', 'Achievements': 'Excellent'}, and a key is added to dictionary dict1 as "Achievements" Key pair with value "excellent".
Modify the value corresponding to the existing key:
dict1={'name': '张三', 'age': 18, '地址': 'China', '成绩': '优秀'} dict1["name"]="李四" print(dict1)
The printed result is {'name': '李思', 'age': 18, 'Address': 'China', 'Achievements': 'Excellent'}, change the value corresponding to the key "name" in the dictionary dict1 from Zhang San to Li Si.
4. Delete dictionary elements The del() method can delete a single element or the dictionary. After deleting the dictionary, the dictionary will no longer exist
Delete a single element:
dict1={'name': '张三', 'age': 18, '地址': 'China', '成绩': '优秀'} del dict1['成绩'] print(dict1)
The printed result at this time is {'name': 'Zhang San', 'age': 18, 'Address': 'China'}, and the key "score" and the corresponding value in the dictionary dict1 are deleted.
Delete dictionary:
dict1={'name': '张三', 'age': 18, '地址': 'China', '成绩': '优秀'} del dict1 print(dict1)
At this time, the printed result is "NameError: name 'dict1' is not defined", which means that dictionary dict1 no longer exists because dictionary dict1 has been deleted.
5. Clear the dictionary. Because del is to delete the dictionary, if you want to clear the dictionary, you can use the dict.clear() method, which means to clear all key pairs in the dictionary.
eg:
dict1={'name': '张三', 'age': 18, '地址': 'China', '成绩': '优秀'} dict1.clear() print(dict1)
The printed result at this time is {}, which means that all values in the dictionary dict1 have been cleared, and the dictionary dict1 is an empty dictionary.
The above is the detailed content of One of the commonly used methods in Python dictionary. For more information, please follow other related articles on the PHP Chinese website!

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.

ToaccesselementsinaPythonlist,useindexing,negativeindexing,slicing,oriteration.1)Indexingstartsat0.2)Negativeindexingaccessesfromtheend.3)Slicingextractsportions.4)Iterationusesforloopsorenumerate.AlwayschecklistlengthtoavoidIndexError.

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version
SublimeText3 Linux latest version

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
