search
HomeBackend DevelopmentPython TutorialAdding and traversing methods of python dictionary key-value pairs

Add key-value pairs

First define an empty dictionary

>>> dic={}

Directly Assign a value to a key that does not exist in the dictionary to add

>>> dic['name']='zhangsan'
>>> dic

{'name': 'zhangsan'}

This method can also be used if the key or value are both variables

>>> key='age'
>>> value=30
>>> dic[key]=value
>>> dic

{'age': 30, 'name': 'zhangsan'}

Here you can see that the data in the dictionary is not arranged in order. If you are interested, you can search for the hash table in the data structure

You can also use the setdefault method of the dictionary

##

>>> dic.setdefault('sex','male')
'male'
>>> key='id'
>>> value='001'
>>> dic.setdefault(key,value)
'001'
>>> dic
{'id': '001', 'age': 30, 'name': 'zhangsan', 'sex': 'male'}

Traverse the dictionary

There are two methods here

Method 1: Get the key first, and then pass dic[key ]Get value

>>> for key in dic:
...   print 'key is %s,value is %s'%(key,dic[key])
...
key is id,value is 001
key is age,value is 30
key is name,value is zhangsan
key is sex,value is male

Method 2: Unpack the tuple list returned by the dictionary items() method in sequence

>>> for key,value in dic.items():
...   print 'key is %s,value is %s'%(key,value)
...
key is id,value is 001
key is age,value is 30
key is name,value is zhangsan
key is sex,value is male

If you are not familiar with list, tuple and sequence unpacking, it is best to Baidu to understand them in depth. You can understand it by combining the arrays, List classes and hash tables you are familiar with in C# or JAVA language

The above method of adding and traversing python dictionary key-value pairs is all the content shared by the editor. , I hope it can give everyone a reference, and I also hope everyone will support the PHP Chinese website.

For more articles related to adding and traversing python dictionary key-value pairs, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Building High-Performance Computing Solutions with PythonBuilding High-Performance Computing Solutions with PythonJul 21, 2025 am 03:17 AM

Pythoncanbeusedeffectivelyforhigh-performancecomputing(HPC)byleveragingspecifictoolsandtechniques.1)UsecompiledextensionslikeNumPy,SciPy,Cython,andNumbaforfasternumericalcomputations.2)TakeadvantageofparallelismwithmultiprocessingforCPU-boundtasksand

Factory Method Pattern in PythonFactory Method Pattern in PythonJul 21, 2025 am 03:15 AM

The factory method pattern is a design pattern that instantiates specific classes through subclass decisions. It defines an interface to create objects, delaying the creation of objects to subclass processing, thereby achieving decoupling. This mode is suitable for scenarios such as hidden object creation details, uncertain future subclass types, and the need to call different objects in a unified interface. The implementation steps include: defining the base class or interface; creating multiple subclasses; writing factory functions or methods that return different instances according to parameters. Factory methods can be further encapsulated into classes to facilitate management of complex logic. When using it, you should pay attention to avoiding too many conditional judgments, preventing business logic from being mixed into the factory, avoiding over-design. It is also recommended to deal with abnormal inputs, keep the logic simple, and use it only when scalability is required.

Building a Chatbot with Python NLTKBuilding a Chatbot with Python NLTKJul 21, 2025 am 03:12 AM

It is feasible to use Python and NLTK as chatbots, but the goals and methods need to be clarified. 1. Install Python and NLTK and download the necessary corpus such as punkt, stopwords and wordnet. 2. The implementation process includes text preprocessing (word segmentation, stop word deactivation, word shape restoration), intent recognition or keyword matching, and response generation. 3. Simple response can be achieved through keyword matching, or classification models can be trained to improve the effect. 4. Extension directions include introducing more powerful NLP tools such as spaCy or Transformers, maintaining Q&A databases, and avoiding too much hardcoded logic. In short, it is suitable for introductory and small projects, with low deployment costs but strong controllability.

Image Processing with Python PillowImage Processing with Python PillowJul 21, 2025 am 03:11 AM

Pillow library image processing is very simple and suitable for daily operations. 1. Install pipinstallpillow and import the Image module to start; 2. You can open the picture and view width, height, format and other information; 3. Use crop to extract specific areas; 4. Use resize to zoom, pay attention to maintaining the proportion and avoiding deformation; 5. Use the draw.text method to add text watermarks, and specify the font path, position and color; 6. Use the paste method to overlay transparent layers in the image watermark; 7. Filter processing supports turning grayscale images, adjusting brightness contrast, etc.; 8. Although the Pillow function is basic, it is practical, and mastering common methods and document query can quickly complete the requirements.

Python for Distributed ComputingPython for Distributed ComputingJul 21, 2025 am 03:03 AM

Python is widely used in distributed computing because of its rich ecosystem and efficient development. 1. Distributed computing is to split tasks into multiple machines to perform to improve efficiency. Python is chosen because it has many libraries, easy to debug, and strong compatibility. 2. Common frameworks include Celery (asynchronous tasks), Dask (data science), PySpark (big data processing), and Ray (high-performance scheduling). 3. Celery can be used to build a simple system: install dependencies, write tasks, start worker, and trigger tasks. 4. Note points include task granularity, data lightweighting, failure retry, monitoring logs and task dependency management.

Python Regular Expressions TutorialPython Regular Expressions TutorialJul 21, 2025 am 03:02 AM

Regular expressions are used in Python to find, match, and replace text patterns. 1. Use re.search and re.match to determine whether the text contains a specific pattern. The former searches for the entire string, while the latter only starts from the beginning. 2. Extract content through brackets, such as using match.group(1) to obtain the required part when extracting the email address; 3. Use re.sub to replace sensitive words or format text, such as replacing the email with [EMAIL]; 4. Notes include escaping special characters, controlling greedy matching, ignoring uppercase and uppercase case and multi-line matching. Mastering these can quickly process text on mobile phones.

Building Cross-Platform Mobile Apps with Python BeeWareBuilding Cross-Platform Mobile Apps with Python BeeWareJul 21, 2025 am 03:01 AM

BeeWare is a tool for developing cross-platform mobile applications using Python, which enables a truly native experience through native controls. 1. It is based on the TogaUI toolkit and Briefcase packaging tool, and supports macOS, Windows, Linux, iOS and Android platforms; 2. Unlike Kivy, Flutter or ReactNative, it directly calls the platform API without bridging; 3. It is suitable for developers familiar with Python to carry out rapid prototype development and data-driven gadget-based app development; 4. The current version is more suitable for small and medium-sized or experimental projects, and there are still restrictions on scenarios with high requirements for complex UI and performance; 5. The steps to get started include installing Be

Implementing Edge Computing Solutions with PythonImplementing Edge Computing Solutions with PythonJul 21, 2025 am 02:56 AM

The core of Python's implementation of edge computing is to bring data processing and decision-making close to data sources, and improve efficiency by deploying lightweight services, executing local inference and establishing a cache upload mechanism. 1. Use Flask or FastAPI to deploy local API services on edge nodes to achieve fast response; 2. Use Python to perform data preprocessing and lightweight AI inference to reduce the amount of uploaded data; 3. Use SQLite to implement local cache and combine asynchronous upload to cope with network instability. At the same time, you need to pay attention to details such as dependency control, model size, retry strategy and resource occupation.

See all articles

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

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.