Detailed Explanation of Nesting Dictionary and List in python

  • 2021-12-12 09:20:25
  • OfStack

Storing dictionaries in lists: 1. Storing multiple dictionaries in lists 2. Accessing dictionary values in lists 3. Traversing access to multiple values 2. Storing lists in dictionaries 1. Accessing list elements in dictionaries 2. Accessing dictionary values (dictionary values are lists) 3. Storing dictionaries 1. Dictionaries cannot be composed of all dictionary elements, and errors will be reported. 2. The values in the dictionary can be composed of dictionaries 4. Small mistakes that are easy to make: summary

First of all, make it clear:

1. Access the elements in the dictionary: dict_name [key]/dict_name. get (key)

2. Elements in access list: list_name [index]

1. Store a dictionary in a list:

1. Storing multiple dictionaries in a list


p={'name':'lin','age':21}
y={'name':'xue','age':20}
c=[p,y]
print(c)

Output:

[{'name': 'Jonh', 'age': 18}, {'name': 'Marry', 'age': 19}]

2. Access the value of the dictionary in the list


print(f"person's name is {people[0].get('name')}")
print(f"{people[1].get('name')}'s age is {people[1].get('age')}")
# First use person[0/1] Access the elements in the list ( Dictionary ), Reuse get Method accesses the value in the dictionary 

Output:

person's name is Jonh
Marry's age is 19

3. Traversing through multiple values


for person in people:                                            
# Assign the dictionaries in the list to person                       
    print(f"{person['name']}'s age is {person['age']}")          
    # Take out that variable in each loop person The keys and values of (a dictionary) 

Output:

Jonh's age is 18
Marry's age is 19

Because there are multiple key-value pairs in the dictionary, there are multiple levels of nesting.

The outer layer nests access to each dictionary in the list, and the inner layer nests access to key-value pairs of each dictionary element.


for person in people:    
    # Nesting again in each traversed dictionary (inner loop) 
    for k,v in person.items():          
        print(f"{k}:{v}")

Output:

name:Jonh
age:18
name:Marry
age:19name:Jonh
age:18
name:Marry
age:19

2. Storing a list in a dictionary

1. Access list elements in the dictionary

First, use list [index] to access the elements in the list, and use dict [key] method to access the values in the dictionary.


favourite_places={
    'lin':['beijing','tianjin'],
    'jing':['chengdu','leshan'],
    'huang':['shenzhen']
}
# To access the values in the dictionary, you can use: dict_name[key]
print(favourite_places['lin'])
# The elements in the access list are indexed: list_name[ Index ]
print(favourite_places['lin'][0].title())

Output:

['beijing', 'tianjin']
Beijing

Iterate through the elements of the list in the dictionary, also using dict_name [key] to access the values (list) in the dictionary first


for i in favourite_places['lin']:     
    print(i.title())

Output:

Beijing
Tianjin

2. Access the values in the dictionary (the values in the dictionary are lists)

Note: Direct access to the values in the dictionary will be presented in the form of a list.


for name,place in favourite_places.items():
    print(f"{name.title()}'s favourite places are {place}")

Output:

Lin's favourite places are ['beijing', 'tianjin']
Jing's favourite places are ['chengdu', 'leshan']
Huang's favourite places are ['shenzhen']

To avoid it, loop nesting is required


for names,places in favourite_places.items():  # Right 3 Key-value pairs go first 1 A big cycle 
    print(f'{names.title()} favourite places are:') # In the big cycle, every 1 Print this sentence at the beginning of the group key-value pair 
    for place in places:      # After that, the value is performed 1 Small loop, printing out each element in the value 
        print(place.title())

Output:

Lin favourite places are:
Beijing
Tianjin
Jing favourite places are:
Chengdu
Leshan
Huang favourite places are:
Shenzhen

3. Store dictionaries in dictionaries

1. The dictionary cannot be composed of all dictionary elements, and an error will be reported.


p={'name':'lin','age':21}
y={'name':'xue','age':20}
c={p,y}
print(c)

TypeError Traceback (most recent call last)
< ipython-input-46-4127ab9ea962 > in < module >
1 p={'name':'lin','age':21}
2 y={'name':'xue','age':20}
---- > 3 c={p,y}
4 print(c)

TypeError: unhashable type: 'dict'

2. Values in a dictionary can be composed of dictionaries


users={
    'a':{'name':'lin','age':21},
    'b':{'name':'xue','age':20}
}
print('----------- Direct access to output -------------------')
print(users['a']['name'],users['a']['age'])
print(users['b']['name'],users['b']['age'])
print('\n----------- Loop nested method output -------------------')
for username,userinfo in users.items():
    print('\n'+username+':')
    for name,age in userinfo.items():
        print(name,age)

Output:

----direct access to output-------
lin 21
xue 20

-----Loop nested method output------------

a:
name lin
age 21

b:
name xue
age 20

4. Small mistakes that are easy to make:

1. Access order: You can use dict_name[key] / dict_name.get(key) The value of the dictionary can be accessed, or the value of the list can be accessed using the list index list_name [index]. But pay attention to which one is outside and which one is inside. Visit the outer layer first, then visit the inner layer. If you visit the inner layer directly, you will make mistakes.

2. The value of the dictionary is a list, and the result of access is to output the whole list, which needs nested loops to traverse the key-value pairs inside.

3. Not all dictionary elements in a dictionary

Summarize

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: