Python Basics - 5. Dictionary

5. Dictionary

  • Dictionary definition

In Python, a dictionary is a series of key value pairs. Each key is associated with a value, and you can use the key to access the associated value. The values associated with keys can be numbers, strings, lists, and even dictionaries. In fact, any Python object can be used as a value in the dictionary.
In Python, dictionaries are represented by a series of key value pairs placed in curly braces ({}).
Key value pairs are two associated values. When you specify a key, Python returns the value associated with it. Keys and values are separated by colons, and key value pairs are separated by commas. In the dictionary, you can store as many key value pairs as you want.

  • Dictionary initialization
    We can define an empty dictionary so that we can add key value pairs to it in batches later.
    When there are too many key value pairs in the initial words in the dictionary we define, we can put the larger dictionary in multiple lines, and each line ends with a colon. It is recommended to add a comma after the last key value pair to prepare for adding key value pairs in the next line in the future. Finally, it's a good idea to indent the back brace so that it aligns with the key value pair.
alien_0 = {}  #Define an empty dictionary
print(alien_0)

favorite_languages = {
   'jen': 'Python',
   'sarah': 'c',
   'edward': 'ruby',
   'phil': 'Python',
   }    #Indents are added to align with key value pairs

print(favorite_languages)

Output:
{}
{'jen': 'Python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'Python'}
  • ACCESS Dictionary

To get the value associated with the key, specify the dictionary name and the value in parentheses.

alien_0 = {'color':'green', 'points':5}
print(alien_0)

alien_0['color'] = 'red'
print(alien_0)

Output:
{'color': 'green', 'points': 5}
{'color': 'red', 'points': 5}
  • Add key value pairs to the dictionary
    To add a key value pair, specify the dictionary name, the key enclosed in square brackets, and the associated value.
    In Python 3.7, the order of elements in the dictionary is the same as that in the definition, that is, the order of elements in the dictionary is consistent with the order of addition.
alien_0 = {'color':'green', 'points':5}
print(alien_0)

alien_0['x_position'] = 0
alien_0['y_position'] = 1
print(alien_0)

Output:
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 1}
  • Delete key value pair
    For information that is no longer needed in the dictionary, you can use the del statement to completely delete the corresponding key value pairs. When using the del statement, you must specify the dictionary name and the key to delete.
alien_0 = {'color':'green', 'points':5}
print(alien_0)

del alien_0['color']
print(alien_0)

Output:
{'color': 'green', 'points': 5}
{'points': 5}
  • Use get() to access values
    When the key value we access may not exist, we should consider using get() instead of square brackets.
    Get (key, default message). Key is required and default message is optional. However, it is recommended to add a prompt message when you do not know whether the key exists.
favorite_languages = {
    'jen': 'Python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'Python',
    }
    
#Find existing key value pairs
sarah = favorite_languages.get('sarah',"No such a student!")  
print(sarah)

#Find non-existent key value pairs
Malong = favorite_languages.get('Malong',"No such a student!")  
print(Malong)

Output:
c
No such a student!
  • Traversal dictionary
    The dictionary may contain millions of key value pairs. Python supports traversal of the dictionary. There are many traversal methods. You can traverse all key value pairs of the dictionary or only keys or values.
    The specific syntax is as follows:
Syntax:
dictionary = {}
#Traverse key value pairs
for k,v in dictionary.items()
#Traversal key
for k in dictionary.keys()
for k in dictionary   #When traversing the dictionary directly, the key is traversed by default
#Traversal value
for v in dictionary.values()
for v in set(dictionary.values)

Among them, items() returns an iteratable key value pair list object, keys() returns an iteratable key list object, and values() returns an iteratable value list object. It is worth mentioning that:

  • When we do not apply any function and directly use the dictionary name, the keys() function is used by default;
  • The list retrieved by values() may be repeated, and you can use set to remove duplication;
  • A set is a data structure that is easily confused with a dictionary, because both are defined with a pair of curly braces. When there is no key value pair in the curly braces, it is likely to be a set. Unlike lists and dictionaries, collections do not store elements in a specific order. The collection does not contain duplicate elements, and can also be iterated with a for loop.
#aggregate
union = {'first','second','third','first'}
print(union)

for item in union:
    print(item)

Output:
{'second', 'third', 'first'}
second
third
first

The following shows how to extract elements from the iterator and generate a list:

dictionary = {
    'jen': 'Python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'Python',
    }

#Get an iteratable list object, and each element is a tuple
items_1 = dictionary.items()
print(items_1)
#The only way to get the element list from it is to iterate through the for loop
items = [item for item in dictionary.items()]
print(items)
#After obtaining the list, you can operate on the list
del items[0]
print(items)
#Tuples can be taken from the list
new_tuple = items[0]
print(new_tuple)
#You can also extract tuples
new_tuple = (1,2)
print(new_tuple)

Output:
[('jen', 'Python'), ('sarah', 'c'), ('edward', 'ruby'), ('phil', 'Python')]
[('sarah', 'c'), ('edward', 'ruby'), ('phil', 'Python')]
('sarah', 'c')
(1, 2)

keys() and values() are shown below:

dictionary = {
    'jen': 'Python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'Python',
    }

#The default of not using keys()
first_keys = [key for key in dictionary]
print(first_keys)
#Use keys() to get keys
second_keys = [key for key in dictionary.keys()]
print(second_keys)

#Using values() directly may result in duplicate values
repeat_values = [value for value in dictionary.values()]
print(repeat_values)
#You can use set() to de duplicate the resulting list of values
unrepeat_values = [value for value in set(dictionary.values())]
print(unrepeat_values)

Output:
['jen', 'sarah', 'edward', 'phil']
['jen', 'sarah', 'edward', 'phil']
['Python', 'c', 'ruby', 'Python']
['ruby', 'Python', 'c']
  • Dictionary list
    Sometimes you need to nest dictionaries in the list, that is, the list of dictionaries. For example, in the alien war game, there may be many colors for aliens, and there are different scores for eliminating different aliens, but we hope that all aliens exist in a list for easy access. We can do the following:
aliens = []
color = ('red', 'yellow', 'blue')
for i in range(5):
    alien = {'color':color[i%3], 'score':(i+1)%3,}
    aliens.append(alien)
print(aliens)

Output:
[{'color': 'red', 'score': 1}, {'color': 'yellow', 'score': 2}, {'color': 'blue', 'score': 0}, {'color': 'red', 'score': 1}, {'color': 'yellow', 'score': 2}]
  • Store list in dictionary
    Sometimes it is necessary to store the list in the dictionary. For example, when guests order at Shaanxi biangbiang noodle restaurant, different guests may have different spicy degrees, different acidity, wide noodles or fine noodles. We hope to store the needs of each guest in the guest's exclusive list:
orders = {}
spicy = ('wei la', 'zhong la', 'te la')
acidity = ('bu jia', 'shao suan', 'duo suan')
noodles = ('kuan', 'xi')

for i in range(5):
   guest = []                     #Note that it should be initialized here, otherwise it will be added all the time
   guest.append(spicy[i%3])
   guest.append(acidity[i%3])
   guest.append(noodles[i%2])
   orders[f"guest{i}"] = guest
print(orders)

Output:
{'guest0': ['wei la', 'bu jia', 'kuan'],
'guest1': ['zhong la', 'shao suan', 'xi'],
'guest2': ['te la', 'duo suan', 'kuan'],
'guest3': ['wei la', 'bu jia', 'xi'], 
'guest4': ['zhong la', 'shao suan', 'kuan']}

Here, we should pay attention to the deep copy and shallow copy of the list:

first_items = [1,2,3]
second_items = first_items[:]
dic = {'first':first_items, 'second':second_items}
print(dic)

#Clear first list
first_items.clear()
print(dic)

Output:
{'first': [1, 2, 3], 'second': [1, 2, 3]}
{'first': [], 'second': [1, 2, 3]}

It can be seen here that after the first list is cleared, the value of the first key value pair of the dictionary is also cleared, which is the problem of shallow replication. Even if the first list exists as the value of the first key value pair of the dictionary, it points to the same memory as the list, so the value disappears after the list is deleted, In contrast, the second deep copy list does not have this problem. While this has problems, it also has advantages in some cases. The advantage is that when we change the value of the list, it will be automatically synchronized in the dictionary, and we don't need to modify the dictionary again.
In the for loop of the previous code example, we put the initialization of the guest list in the for loop. This has the effect that a memory area will be reallocated at the beginning of each loop, so as to avoid the problem of adding data at the end of a list and corresponding deep replication.

  • Store dictionary in dictionary
    Sometimes we need to add a dictionary to the dictionary. The difference between this and adding a list in the dictionary is that the data to be added in the dictionary has keywords. For example, in a class, each student has a class and student number. As follows:
students = {
   'xiao ming':{					#Use a colon instead of an equal sign here
       'class':1,
       'number':111,
   },						        #Be careful not to forget the comma
   'xiao hong':{
       'class':2,
       'number':222
   },
}

print(students)

Output:
{'xiao ming': {'class': 1, 'number': 111},
'xiao hong': {'class': 2, 'number': 222}}





Keywords: Python

Added by epilator on Tue, 19 Oct 2021 01:51:39 +0300