The value of a dictionary in python can be modified. First of all, we have to know what a modified dictionary is
Modify 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 newentry
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
The output of the above example:
dict['Age']:8
dict['School']: DPS School
When the key in the dictionary exists, you can access the value corresponding to the changed key in the dictionary through the dictionary name + subscript. If the key does not exist, an exception will be thrown. If you want to directly add elements to the dictionary, you can directly add dictionary elements by using dictionary name + subscript + value. Only write the key and want to assign the key later this way will throw an exception.
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'}
Example extension:
Use the updata 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} Replaced{1:'apple',2:'banana'}
So far, this article on whether the value of the python dictionary can be modified is introduced. For more related python dictionary values, whether the value can be modified, please search ZaLou.Cn
Recommended Posts