Python Dictionary of Dictionary operation details

  • 2020-04-02 13:27:46
  • OfStack

Python dictionaries are another mutable container model and can store objects of any type, such as strings, Numbers, tuples, and other container models.

Create a dictionary

A dictionary consists of pairs of keys and corresponding values. Dictionaries are also called associative arrays or hash tables. The basic syntax is as follows:

Dict = {' Alice ':' 2341 ', 'Beth' : '9102', 'enough', '3258'}

You can also do this to create a dictionary

Dict1 = {' ABC ': 456}
Dict2 = {' ABC ': 123, 98.6:37}

Note:

Each key is separated from the value by a colon (:), each pair is separated by a comma, each pair is separated by a comma, and the whole is enclosed in curly braces ({}).
Keys must be unique, but values are not.
Values can be of any data type, but must be immutable, such as strings, Numbers, or tuples.

Access the values in the dictionary

Place the corresponding key in a familiar square bracket, as shown in the following example:


dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age'];
# Output results of the above examples: 
#dict['Name']: Zara
#dict['Age']: 7

If you use a key that is not in the dictionary to access the data, the error will be output as follows:

Dict = {' Name ':' Zara ', 'Age: 7,' Class ':' First '};

Print "dict [' Alice '] :" the dict [' Alice '];

Output results of the above examples:

# KeyError: 'Alice'

Third, modify the dictionary

Adding new content to the dictionary is done by adding new key/value pairs and modifying or removing existing key/value pairs as follows:


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 School

Delete dictionary elements

You can delete a single element or you can empty a dictionary.
Shows deleting a dictionary with the del command, as shown in the following example:


dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

del dict['Name']; #  The delete key is 'Name' The entry of 
dict.clear();  #  Empty the dictionary of all entries 
del dict ;  #  Delete the dictionary 

print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
# But this throws an exception because of the del Post dictionary no longer exists: 
dict['Age']:

Five, the characteristics of the dictionary key

Dictionary values can take any python object without restriction, either a standard object or a user-defined one, but not a key.
Two important points to remember:

1) the same key is not allowed to appear twice. If the same key is assigned twice during creation, the latter value will be remembered, as shown in the following example:


dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};

print "dict['Name']: ", dict['Name'];
# Output results of the above examples: 
#dict['Name']: Manni

2) the key must be immutable, so it can be used as a number, string or tuple, so it cannot be used as a list, as shown in the following example:


dict = {['Name']: 'Zara', 'Age': 7};

print "dict['Name']: ", dict['Name'];
# Output results of the above examples: 
#TypeError: list objects are unhashable

Dictionary built-in functions & methods

The Python dictionary contains the following built-in functions:

CMP (dict1, dict2) # compares two dictionary elements.
Len (dict) # calculates the number of dictionary elements, the total number of keys.
STR (dict) # outputs a printable string representation of the dictionary.
Type (variable) # returns the type of the input variable, or the dictionary type if the variable is a dictionary.

The Python dictionary contains the following built-in methods:

Radiansdict. clear() # removes all elements in the dictionary
Radiansdict.copy () # returns a shallow copy of a dictionary
Radiansdict. fromkeys() # create a new dictionary with the element in the sequence seq as the key for the dictionary and val as the initial value for all the keys in the dictionary
Radiansdict.get (key, default=None) # returns the value of the specified key, if the value is not in the dictionary
Radiansdict. has_key(key) # returns true if the key is in the dictionary dict, or false otherwise
Radiansdict.items () # returns a traversable array of tuples (keys, values) in a list
Radiansdict.keys () # returns all the keys of a dictionary in a list
Radiansdict. setdefault(key, default=None) # is similar to get(), but if the key does not already exist in the dictionary, the key is added and the value set to default
Radiansdict. update(dict2) # updates the key/value pair of the dictionary dict2 to the dict
Radiansdict.values () # returns all the values in the dictionary in a list

Seven, the dictionary practice code


print('''|--- Welcome to the address book program ---|
|---1 ,   Contact information inquiry ---|
|---2 ,   Insert a new contact ---|
|---3 ,   Delete existing contacts ---|
|---4 ,   Exit the address book program ---|''')
addressBook={}# Define address book 
while 1:
 temp=input(' Please enter the instruction code: ')
 if not temp.isdigit():
  print(" The input instruction is wrong. Please follow the prompt ")
  continue
 item=int(temp)# Convert to Numbers 
 if item==4:
  print("|--- Thanks for using the address book program ---|")
  break
 name = input(" Please enter the contact name :")
 if item==1:
  if name in addressBook:
   print(name,':',addressBook[name])
   continue
  else:
   print(" This contact does not exist! ")
 if item==2:
  if name in addressBook:
   print(" The name you entered already exists in the address book -->>",name,":",addressBook[name])
   isEdit=input(" Whether to modify contact information (Y/N ) :")
   if isEdit=='Y':
    userphone = input(" Please enter contact number: ")
    addressBook[name]=userphone
    print(" Contact modified successfully ")
    continue
   else:
    continue
  else:
   userphone=input(" Please enter contact number: ")
   addressBook[name]=userphone
   print(" Contact person joined successfully! ")
   continue

 if item==3:
  if name in addressBook:
   del addressBook[name]
   print(" Delete successfully! ")
   continue
  else:
   print(" Contact does not exist ")

Related articles: