Python basics: (five) dictionaries


        Presumably there are some basic knowledge in the previous ones, and my friends should have confidence in the next study. The previous ones are relatively basic. Students with c foundation may understand it better, but it doesn’t matter that bloggers write dry goods, as long as you Read more, type more code, practice makes perfect.

1. Dictionary definition

1.1 Definition

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. Associated with keys can be numbers, strings, lists, or even dictionaries. In fact, any python object can be used as a value in a dictionary.

1.2 Grammar

Grammar :

变量 = {
    
    '键1':'值1',
		'键2':'值2',
		'键3':'值3',
		...
		}

ps: The simplest dictionary has only one key-value pair. The example in this article takes the alien in the python textbook as an example.

2. Using a dictionary

2.1 Accessing the values ​​in the dictionary

alien = {
    
    'color':'green',
         'points':5,
         'x_position':0,
         'y_position':25,}
print(alien['color'])
print(alien['points'])
print(alien)

insert image description here

2.2 Add key-value pairs

The addition of key-value pairs is to use the assignment statement to add from the end in turn, and a little deepening is a loop or the like.

2.2.1 Grammar:
字典变量['键'] =
>>> alien = {
    
    'color':'green','points':5,}
>>> print(alien)
{
    
    'color': 'green', 'points': 5}
>>> alien['x_position'] = 0
>>> alien['y_position'] = 25
>>> print(alien)
{
    
    'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
2.2.2tips: You can create an empty dictionary first, or you can add key-value pairs.
>>> alien ={
    
    }
>>> print(alien)
{
    
    }
>>> alien['color'] = 'green'
>>> alien['x_position'] = 0
>>> print(alien)
{
    
    'color': 'green', 'x_position': 0}

insert image description here

2.2.3 Modify the value in the dictionary

Just use the assignment statement to overwrite the key-value pair.

alien = {
    
    'color':'green',}
print(alien)
alien['color'] = 'yellow'
print(alien)

insert image description here

2.3 Delete key-value pairs

For information that is no longer needed in the dictionary, you can use the del statement to permanently delete. After deletion, the key and value pairs of the key value will disappear at the same time.

2.3.1 Grammar:
del 字典变量['键']
>>> alien = {
    
    'color':'green','points':5,'x_position':0,'y_position':25,}
>>> print(alien)
{
    
    'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
>>> del alien['x_position']
>>> del alien['y_position']
>>> print(alien)
{
    
    'color': 'green', 'points': 5}

insert image description here

2.4 Accessing values ​​using get()

2.4.1 Description:

When the key you access does not exist in the dictionary, an error will be reported, but when you use get() to access, if there is no key, a default value will be returned.

>>> alien = {
    
    'color':'green','points':5,'x_position':0,'y_position':25,}
>>> print(alien['hhh'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'hhh'

insert image description here

2.4.2 Syntax
get('键''没有的话返回这段话!')

practice :

>>> alien = {
    
    'color':'green','points':5,'x_position':0,'y_position':25,}
>>> print(alien['hhh'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'hhh'
>>> print(alien.get('hhh','没有的话返回这句话!'))
没有的话返回这句话!

insert image description here

3. Traversing the dictionary

3.1 Use items() to access key-value pairs

"""声明两个变量,key(键),value(值)"""
alien = {
    
    'color':'green','points':5,'x_position':0,'y_position':25,}
for key,value in alien.items():
    print(f"key:{
      
      key}")
    print(f"value:{
      
      value}\n")

insert image description here

3.2 Use keys() to access the keys in the dictionary

alien = {
    
    'color':'green','points':5,'x_position':0,'y_position':25,}
for key in alien.keys():
    print(f"key:{
      
      key}")

insert image description here

3.3 Access the keys in the dictionary without using keys()

alien = {
    
    'color':'green','points':5,'x_position':0,'y_position':25,}
for key in alien:
    print(f"key:{
      
      key}")
   

insert image description here

3.4 Use sorted() to traverse all the keys in the dictionary in a specific order (a->b->c...)

Usage specification : sorted(dictionary variable.keys())

alien = {
    
    'color':'green','points':5,'x_position':0,'y_position':25,}
for key in sorted(alien.keys()):
    print(f"key:{
      
      key}")
"""
不使用.keys()结果一样
alien = {'color':'green','points':5,'x_position':0,'y_position':25,}
for key in sorted(alien):
    print(f"key:{key}")

"""

insert image description here

3.5 Use values() to traverse all values ​​in the dictionary

ps: analogy keys()

alien = {
    
    'color':'green','points':5,'x_position':0,'y_position':25,}
for value in alien.values():
    print(f"value:{
      
      value}")

insert image description here
ps: This method extracts all the values ​​in the dictionary, regardless of whether the values ​​are repeated. If you want to avoid duplication, you can use the set set(), which is the same as sorted().

3.6 Use set() to avoid duplication of values ​​in the traversed dictionary

alien = {
    
    'color':'green','points_0':5,'points_1':5,'points_2':5,}
for value in set(alien.values()):
    print(f"value:{
      
      value}")

insert image description here

3.7tips: Create a collection

Explanation: Sets and dictionaries are easy to confuse, because they are defined with "{}". When there is no key-value pair in the brackets, the storage is likely to be a set. Unlike lists and dictionaries, sets will not be stored in specific Store elements sequentially.

jihe = {
    
    'I','love','python'}
print(jihe)

insert image description here

Four. Nesting

4.1 Nested dictionaries in dictionaries

ps: A key corresponds to a value. When a value is composed of information of multiple key-value pairs, the value is represented by a dictionary.

total = {
    
    'cars':{
    
    'like_1':'aodi',
                 'like_2':'bmw',
                 },
        'colors': {
    
    'like':'red',
                  'unlike':'blue',
                  },
           }
for key,value in total.items():
    print(f"key:{
      
      key}")
    print(f"value:{
      
      value}\n")

insert image description here

4.2 Nested lists in dictionaries

ps: When a key corresponds to multiple values, the value is represented by a list.

total = {
    
    'cras':['bmw','aodi'],
           'colors':['red','yellow','green'],
           }
for key,value in total.items():
    print(f"key:{
      
      key}")
    print(f"value:{
      
      value}\n")

insert image description here

4.3 Nested dictionaries in lists (lists of dictionaries)

eg

alien_0={
    
    'color':'green',
         'points':5,
         }
alien_1={
    
    'color':'yellow',
         'points':10,
         }
alien_2={
    
    'color':'red',
         'points':15,
         }
aliens = [alien_0,alien_1,alien_2]
for alien in aliens:
    print(alien)

insert image description here

Generate aliens in batches :

aliens =[]
for alien in range(5): #批量生成五个外星人
    new_alien = {
    
    'colors':'green',
           'points':5,
           }
    aliens.append(new_alien) #添加到空列表的末尾
"""打印外星人"""
for alien in aliens:
    print(alien)

insert image description here
ps: Master some basic knowledge first, and then use the knowledge you have learned in the project to deepen your understanding, from easy to difficult.

Guess you like

Origin blog.csdn.net/qq_63913621/article/details/129155054