Summary of python Dictionary Change value Value Method

  • 2021-06-29 11:28:58
  • OfStack

In this article today, we will look at a dictionary in python, in which I will explain how to modify the python dictionary and give examples of how to modify the values in the python dictionary.Say nothing more. Let's get into the article.

First we have to know what modifying a dictionary is

Modify Dictionary

The way to add new content to a dictionary is to add new key/value pairs and 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'];

The above example outputs the results:


dict['Age']: 8

dict['School']: DPS School

When a key in a dictionary exists, the value corresponding to the key change in the dictionary can be accessed by the dictionary name + subscript, and an exception will be thrown if the key does not exist.If you want to add elements directly to a dictionary, you can add dictionary elements directly by using dictionary name + subscript + value. Writing keys only throws an exception if you want to assign keys later.


>> > 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 updata method to add update to the current dictionary for key-value pairs with corresponding keys in the 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} Replaced {1: 'apple', 2: 'banana'}


Related articles: