Home  >  Article  >  Backend Development  >  How to change value in python dictionary

How to change value in python dictionary

silencement
silencementOriginal
2019-06-20 15:16:207316browse

How to change value in python dictionary

In today's article, we will learn about the dictionary in python. In this article, I will explain how to modify the python dictionary, and give examples of how to modify the python dictionary. value. Without further ado, let’s get started with the article.

First we have to know what is a modified dictionary

Modify dictionary

The way to add new content to the dictionary is to add new key/value pairs, modify or delete The existing key/value pair is 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'];

The output result of the above example is:

dict['Age']:  8
dict['School']:  DPS School

When the key in the dictionary exists, you can access the value corresponding to the key in the dictionary by subscripting the dictionary name. , an exception will be thrown if the key does not exist. 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] = &#39;grap&#39;
>> > a
{1: &#39;apple&#39;, 2: &#39;banana&#39;, 3: &#39;pear&#39;, 4: &#39;orange&#39;, 6: &#39;grap&#39;}

2. Use the updata 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;}


##

The above is the detailed content of How to change value in python dictionary. For more information, please follow other related articles on 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