In this article, we'll look at the dictionaries in Python, and in this article I'll
Python dictionaryModify the instructions and illustrate how to modify
Python dictionaryValues within the. Don't say much nonsense, let's get into the article.
First we need to know what a modified dictionary is.
Modify Dictionary
The way to add new content to a dictionary is to add a new key/value pair, modify or delete an existing key/value pair as follows:
#!/usr/bin/pythondict = {' Name ': ' Zara ', ' age ': 7, ' Class ': ' First '};d ict[' age ' = 8; # Update existing entrydict[' School '] = "DPS School"; # ADD New Entryprint "dict[' age '):", dict[' age '];p rint "dict[' School ']:", dict[' School '];
The result of the above example output:
Dict[' age ': 8dict[' School ': DPS School
1. When a key in a dictionary exists, the value of the modifier 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 an element directly to the dictionary, you can add the dictionary element directly with the dictionary name + subscript + value, and the write-only key will throw an exception if you want to assign a value to the key 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 '}>&G T > a[2] ' banana ' >> > A[5]traceback (mostrecentcalllast): File "<pyshell#31>", Line1, 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 an update to the current dictionary with 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: ' or Ange ', 6: ' Grap '} #{1:10,2:20} replaced {1: ' Apple ', 2: ' Banana '}
The above is all the content of this article, the dictionary in Python is modified. Hope that the content and the examples given can help you.
For more information, please visit the PHP Chinese Web Python tutorial section.