Home Backend Development Python Tutorial How to change key-value pairs in python dictionary

How to change key-value pairs in python dictionary

Jun 15, 2019 pm 05:28 PM
python dictionary key value pair

How to change key-value pairs in python dictionary?

Related recommendations: "python Video"

How to change key-value pairs in python dictionary

Modify Dictionary

To Dictionary The way to add new content is to add new key/value pairs, modify or delete existing key/value pairs. The following examples:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
 
dict['Age'] = 8;  # update existing entry
dict['School'] = "DPS School";  # Add new entry
 
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
Copy after login

The output results of the above examples:

dict['Age']:  8
dict['School']:  DPS School
Copy after login

1. in the dictionary When the key exists, you can access the value corresponding to the key in the dictionary through the dictionary name subscript. If the key does not exist, an exception will be thrown. If you want to add elements directly to the dictionary, you can add dictionary elements directly using the dictionary name subscript value. If you only write the key and assign the key value later, an exception will be thrown.

>> > a
['apple', 'banana', 'pear', 'orange']
>> > a = {1: 'apple', 2: 'banana', 3: 'pear', 4: 'orange'}
>> > a
{1: 'apple', 2: 'banana', 3: 'pear', 4: 'orange'}
>> > a[2]
'banana'
>> > a[5]
Traceback(most
recent
call
last):
File
"<pyshell#31>", line
1, in < module >
a[5]
KeyError: 5
>> > a[6] = &#39;grap&#39;
>> > a
{1: &#39;apple&#39;, 2: &#39;banana&#39;, 3: &#39;pear&#39;, 4: &#39;orange&#39;, 6: &#39;grap&#39;}
Copy after login

2. Use the update method to add the key-value pairs with corresponding keys in the dictionary to the current dictionary

>>> a
{1: &#39;apple&#39;, 2:&#39;banana&#39;, 3: &#39;pear&#39;, 4: &#39;orange&#39;, 6: &#39;grap&#39;}  
>>>a.items() 
dict_items([(1,&#39;apple&#39;), (2, &#39;banana&#39;), (3, &#39;pear&#39;), (4, &#39;orange&#39;), (6, &#39;grap&#39;)])  
>>>a.update({1:10,2:20})  
>>> a  
{1: 10, 2: 20,3: &#39;pear&#39;, 4: &#39;orange&#39;, 6: &#39;grap&#39;}  
#{1:10,2:20}替换了{1: &#39;apple&#39;, 2: &#39;banana&#39;}
Copy after login

The above is the detailed content of How to change key-value pairs in python dictionary. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

How to use AWS Glue crawler with Amazon Athena How to use AWS Glue crawler with Amazon Athena Apr 09, 2025 pm 03:09 PM

As a data professional, you need to process large amounts of data from various sources. This can pose challenges to data management and analysis. Fortunately, two AWS services can help: AWS Glue and Amazon Athena.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

How to view all keys in redis How to view all keys in redis Apr 10, 2025 pm 07:15 PM

To view all keys in Redis, there are three ways: use the KEYS command to return all keys that match the specified pattern; use the SCAN command to iterate over the keys and return a set of keys; use the INFO command to get the total number of keys.

How to implement the underlying redis How to implement the underlying redis Apr 10, 2025 pm 07:21 PM

Redis uses hash tables to store data and supports data structures such as strings, lists, hash tables, collections and ordered collections. Redis persists data through snapshots (RDB) and append write-only (AOF) mechanisms. Redis uses master-slave replication to improve data availability. Redis uses a single-threaded event loop to handle connections and commands to ensure data atomicity and consistency. Redis sets the expiration time for the key and uses the lazy delete mechanism to delete the expiration key.

How to clean all data with redis How to clean all data with redis Apr 10, 2025 pm 05:06 PM

How to clean all Redis data: Redis 2.8 and later: The FLUSHALL command deletes all key-value pairs. Redis 2.6 and earlier: Use the DEL command to delete keys one by one or use the Redis client to delete methods. Alternative: Restart the Redis service (use with caution), or use the Redis client (such as flushall() or flushdb()).

How to use the redis command How to use the redis command Apr 10, 2025 pm 08:45 PM

Using the Redis directive requires the following steps: Open the Redis client. Enter the command (verb key value). Provides the required parameters (varies from instruction to instruction). Press Enter to execute the command. Redis returns a response indicating the result of the operation (usually OK or -ERR).

See all articles