Home >Backend Development >Python Tutorial >How to modify the value inside the python dictionary? Summary of 2 ways to modify values in Python dictionary
In today's article, we will learn about the dictionary in python. In this article, I will explain the modification of python dictionary, and give examples of how to modify the python dictionary##. The value within #. Without further ado, let’s get started with the article.
First we have to know what is modifying a dictionaryModifying the dictionary
The way to add new content to the dictionary is to add new key/value pairs. Modify or delete existing key/value pairs as follows:# !/usr/bin/python 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'];Output results of the above examples:
dict['Age']: 8 dict['School']: DPS School1. When the keys in the dictionary exist, you can access the dictionary by subscripting the dictionary name. Change the value corresponding to the key. 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 ['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] = 'grap' >> > a {1: 'apple', 2: 'banana', 3: 'pear', 4: 'orange', 6: 'grap'}2. Use the update method to add the key-value pairs with corresponding keys in the dictionary to the current dictionary
>>> a
{1: 'apple', 2:'banana', 3: 'pear', 4: 'orange', 6: 'grap'} >>>a.items() dict_items([(1,'apple'), (2, 'banana'), (3, 'pear'), (4, 'orange'), (6, 'grap')]) >>>a.update({1:10,2:20}) >>> a {1: 10, 2: 20,3: 'pear', 4: 'orange', 6: 'grap'} #{1:10,2:20}替换了{1: 'apple', 2: 'banana'}That’s it All the content discussed in this article, dictionary modification in python. I hope what I said and the examples I gave can be helpful to you. For more related knowledge, please visit the
Python tutorial column on the php Chinese website.
The above is the detailed content of How to modify the value inside the python dictionary? Summary of 2 ways to modify values in Python dictionary. For more information, please follow other related articles on the PHP Chinese website!