Python novice learning: super detailed dictionary introduction (dictionary definition, storage, modification, element traversal and nesting)

1. Introduction to Dictionary

A dictionary is represented by a series of key-value pairs enclosed in curly braces { } .

1.1 Create a dictionary

Use a pair of empty curly braces to define a dictionary , and then add each key-value pair separately.

alien = {
    
    }
alien['color'] = 'green'
alien['points'] = 5
print(alien)

insert image description here

1.2 Accessing the values ​​in the dictionary

Elements in a dictionary consist of key-value pairs. To get the value associated with a key, specify the dictionary name followed by the key in square brackets.

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

insert image description here
A dictionary can contain any number of key-value pairs.

1.3 Add key-value pairs

A dictionary is a dynamic structure where key-value pairs can be added at any time. To add key-value pairs, specify the dictionary name, the key enclosed in square brackets, and the associated value.

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

insert image description here

1.4 Modify the value in the dictionary

To modify a value in a dictionary, specify the dictionary name, the key enclosed in square brackets, and the new value associated with that key.

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

insert image description here

example

Track the position of an alien that can move at different speeds, set the moving speed of the alien to three speeds of 'fast, slow, and medium', move to the right 3m at a time at a fast speed, move 1m to the right at a time at a slow speed, and medium The speed moves to the right 2m at a time, the alien's position is (0,25), what are the positions of the robot after moving at different speeds?

alien = {
    
    'name':'alen','color':'red','x_position':0,'y_position':25,'speed':'medium'}
position = (alien['x_position'],alien['y_position'])
print(f"The position is {
      
      position}")
if alien['speed'] == 'fast':
    x = 3
elif alien['speed'] == 'medium':
    x = 2
elif alien['speed'] == 'slow':
    x = 1
alien['x_position'] += x
new_position = (alien['x_position'],alien['y_position'])
print(f"The new position with the speed of {
      
      alien['speed']} is {
      
      new_position}")

The position coordinates when the speed is medium are set in the code.
insert image description here
Modify the value corresponding to the speed key in the dictionary to get the position of different speeds.
insert image description here

1.5 Delete key-value pairs

Use the del statement to delete unwanted key-value pairs

alien = {
    
    'name':'alen','color':'red','x_position':0,'y_position':25,'speed':'fast'}
print(alien)
del alien['name']
print(alien)

insert image description here

1.6 Dictionaries of multiple similar objects

In the previous example, the dictionary stores multiple attributes of an object (alien). You can also use a dictionary to store the same information of many objects, such as using a dictionary to store everyone's favorite programming language.

favorite_lauguague = {
    
    
    'ken':'python',
    'jack':'c++',
    'will':'java',
    'mary':'ruby'
}
print(f"Will's favorite lauguague is {
      
      favorite_lauguague['will'].title()}")

The multi-line definition shown above can be used when defining long dictionaries.

1.7 Accessing values ​​using get()

  • get(key, the value returned when the specified key does not exist)

This function handles exceptions when the desired key does not exist.

favorite_languague = {
    
    
    'ken':'python',
    'jack':'c++',
    'will':'java',
    'mary':'ruby'
}
print(favorite_languague)
languague = favorite_languague.get('diane','ERROR!No Such People Named Diane!')
print(languague)
favorite_languague['diane'] = 'c'
languague = favorite_languague.get('diane','ERROR!No Such People Named Diane!')
print(favorite_languague)
print(languague)

In the above code:

  • When using get to query a key that does not exist (diane does not exist), it will return the string defined in the get method when an exception occurs;
  • When you use get to query the existing key (assign the corresponding value c to the diane key), the value corresponding to the key will be returned.

1.8 Exercises

insert image description here

print('6-1')
people = {
    
    
    'first_name':'winnie',
    'last_name':'ma',
    'age':22,
    'city':'zibo'
}
print(people)

print('6-2')
favorate_numbers={
    
    
    'will':5,
    'jack':10,
    'diane':6,
    'peter':51,
    'mary':8
}

Second, traverse the dictionary

2.1 Traverse all key-value pairs

Iterate over all key-value pairs using a for loop and the items method .

for key, value in dictionary.items( )

  • Declare two variables key and value in the for loop to represent the key and value, and you can use any variable name (such as k, v, etc.).
  • The items method returns a list of key-value pairs, and the returned values ​​are assigned to two variables.
user_0 = {
    
    
    'username' : 'jack',
    'age' : 20,
    'city' : 'los angeles'
}
for key,value in user_0.items():
    print(key,value)

insert image description here

example

Print what is everyone's favorite language. The two variable names used here correspond to the variables, namely name and language.

favorite_languages = {
    
    
 'jen': 'python',
 'sarah': 'c',
 'edward': 'ruby',
 'phil': 'python',
 }
for name,lauguage in favorite_languages.items():
    print(f"{
      
      name.title()}'s favorate language is {
      
      lauguage.title()}.")

2.2 Traverse all keys in the dictionary

keys( ) : Returns a list containing all the keys in the dictionary.

favorite_languages = {
    
    
  'jen': 'python',
  'sarah': 'c',
  'edward': 'ruby',
  'phil': 'python',
 }
for name in favorite_languages.keys():
  print(name.title())

insert image description here
The keys() method can not only be used to traverse, but also can be used to determine whether the key is contained in the dictionary.

favorite_languages = {
    
    
  'jen': 'python',
  'sarah': 'c',
  'edward': 'ruby',
  'phil': 'python',
 }

if 'will' not in favorite_languages.keys():
  print('Will, please enter your name!')

2.3 Traverse all the keys in the dictionary in a specific order

Sort the keys using the sorted method: sorted( dictionary.keys() )

favorite_languages = {
    
    
  'jen': 'python',
  'sarah': 'c',
  'edward': 'ruby',
  'phil': 'python',
 }
for name in sorted(favorite_languages.keys()):
  print(f"{
      
      name.title()}, thank you!")

You can see that the output names are sorted alphabetically.

insert image description here

2.4 Traverse all values ​​in the dictionary

The values( ) method returns a list of values.

favorite_languages = {
    
    
  'jen': 'python',
  'sarah': 'c',
  'edward': 'ruby',
  'phil': 'python',
  'will' : 'python'
 }
for lauguage in sorted(favorite_languages.values()):
  print(lauguage)

insert image description here
You can see that there are duplicate items in Python in the value output by this method. If you want to remove duplicate items, you can use the set method to remove duplicate items.

How to deduplicate the output value

set( ): set, each element in the set is unique.

favorite_languages = {
    
    
  'jen': 'python',
  'sarah': 'c',
  'edward': 'ruby',
  'phil': 'python',
  'will' : 'python'
 }
for lauguage in set(favorite_languages.values()):
  print(lauguage)

insert image description here
You can see that the Python duplicates have been removed.

gather

Sets, like dictionaries, are defined using curly braces. When there are no key-value pairs inside the curly braces, the definition is likely to be a collection.

lauguages = {
    
    'python','python','c'}
print(lauguages)

You can see that there are duplicate elements in the defined collection, and the collection output will be automatically deduplicated.

insert image description here

2.5 Exercises

insert image description here

the code

print('6-5')
rivers_countrys = {
    
    
  'nile':'egypt',
  'changjiang':'china',
  'amazon':'brazil'
}
for river,country in rivers_countrys.items():
  print(f"The {
      
      river.title()} runs through {
      
      country.title()}.")

print('6-6')
favorite_languages = {
    
    
  'jen': 'python',
  'sarah': 'c',
  'edward': 'ruby',
  'phil': 'java',
  'will' : 'python'
 }
names = ['will','jen','peter','ken']
for name in names:
  if name in favorite_languages.keys():
    print(f"Dear {
      
      name.title()}, thank you!")
  else:
    print(f'Dear {
      
      name.title()}, please joy our party.')

output

insert image description here

3. Nested use of dictionaries and lists

3.1 Storing dictionaries in lists

Joining us requires a multi-person list, and each person needs to include their name, age, and gender information, so how to coordinate and manage these multi-person information?

The answer is to create a list of users, where each user is a dictionary containing various information about the user.

Manually enter a dictionary into a list

user_1 = {
    
    'name':'will','age':40,'gender':'male'}
user_2 = {
    
    'name':'diane','age':37,'gender':'female'}
user_3 = {
    
    'name':'cary','age':25,'gender':'male'}

users = [user_1,user_2,user_3]

for user in users:
  print(user)

insert image description here

Automatically generate multiple people's dictionaries and add them to the list

If you need to generate more user information, you can first create an empty list of users, and then use the range method to generate the required number of users.

users = []
for number in range(30):
  new_user = {
    
    'name':'will','age':40,'gender':'male'}
  users.append(new_user)
  #显示前5个
for user in users[:5]:
  print(user)

Use range(30) to automatically generate 30 user dictionaries, and then use the append method to add them to the users list in turn.

The figure below shows the first five user dictionaries in the users list before output.

insert image description here

3.2 Storing lists in dictionaries

If you want to build a dictionary of programming languages ​​that people master, each person may master multiple programming languages, so you need a key corresponding to multiple values, and you can nest lists in the dictionary.

people_lauguages = {
    
    
  'will' : ['python','c'],
  'peter' : ['c++','java'],
  'ken' : ['ruby','c++','go']
}
for people,lauguages in people_lauguages.items():
  print(f"{
      
      people.title()} can master:",end=" ")
  for lauguage in lauguages:
    print(lauguage.title(),end=" ")
  else:
    print("\n")

insert image description here

Output the length of each list in the dictionary

Use the values ​​method to get the list in the dictionary, and then use the len method to count the length of the list.

people_lauguages = {
    
    
  'will' : ['python','c'],
  'peter' : ['c++','java'],
  'diane' : ['python'],
  'ken' : ['ruby','c++','go'],
  'cary' : ['c']
}

for lauguages in people_lauguages.values():
  print(len(lauguages))

insert image description here

practise

If it is necessary to further judge the number of languages ​​that people have mastered, if only one language can be mastered, then output the sentence "You need to keep learning".

people_lauguages = {
    
    
  'will' : ['python','c'],
  'peter' : ['c++','java'],
  'diane' : ['python'],
  'ken' : ['ruby','c++','go'],
  'cary' : ['c']
}
for people,lauguages in people_lauguages.items():
  if len(lauguages) == 1:
    print(f"{
      
      people.title()}, you need to learn more lauguages!",end=" ")
  elif len(lauguages) >=2:
    print(f"{
      
      people.title()}, you already master",end=" ")
    for lauguage in lauguages:
      print(lauguage,end=" ")
  else:
    print("error!")
  print("\n")

insert image description here

3.3 Storing dictionaries within dictionaries

Dictionaries of the same structure are nested within dictionaries.

users = {
    
    
  'mary' : {
    
    
    'age':21,
    'gender':'female'
  },
  'will' : {
    
    
    'age':40,
    'gender':'male'
  }
}

for name, name_info in users.items():
  print(f"{
      
      name}")
  for age,gender in name_info.items():
    print(age,gender)

insert image description here

4. Exercises

insert image description here
insert image description here
6-7

#6-7
people_1 = {
    
    
    'first_name':'winnie',
    'last_name':'ma',
    'age':22,
    'city':'zibo'
}
people_2 = {
    
    
    'first_name':'will',
    'last_name':'zhao',
    'age':40,
    'city':'qingdao'
}
people_3 = {
    
    
    'first_name':'mary',
    'last_name':'wang',
    'age':20,
    'city':'jinan'
}
people = [people_3,people_2,people_1]

for p in people:
  for k,v in p.items():
      print(k,v)

insert image description here
6-8
insert image description here

6-9

#6-9
favorate_place = {
    
    
    'peter' : ['america'],
    'cary' : ['china','brazil','italy'],
    'diane' : ['india','france']
}
for name,places in favorate_place.items():
    if len(places) == 1:
        print(f"{
      
      name.title()}'s avorate place is {
      
      places[0].title()}!")
    elif len(places)>=2:
        print(f"{
      
      name.title()}'s favorate places are",end=" ")
        i=1
        for place in places:
            if i<=len(places)-1:
                print(f"{
      
      place.title()}",end=" and ")
                i+=1
            else:
                print(f"{
      
      place.title()}",end="!\n")
    else:
        print("error")

insert image description here

6-11

#6-11
cities = {
    
    
    'zibo':{
    
    
        'country':'china',
        'num_people':9000,
        'food':'barbecue'
    },
    'jinan':{
    
    
        'country':'china',
        'num_people':500,
        'food':'meet'
    },
    'qingdao':{
    
    
        'country':'china',
        'num_people':6300,
        'food':'sea food'
    }
}
for city,city_info in cities.items():
    print(f"{
      
      city.title()}")
    for k,v in city_info.items():
        print(k,v)

insert image description here

Guess you like

Origin blog.csdn.net/weixin_45662399/article/details/132101895
Recommended