Explanation of python Dictionary and List Nesting Usage

  • 2021-11-13 08:23:42
  • OfStack

Directory List (List) Common Way Dictionary (dictionary) Common Way Combination Use List Nested List List Nested Dictionary Dictionary Nested Dictionary Dictionary Nested List Nested When to Use References

The use of dictionaries and lists in python should be the most commonly used in data processing, and these two proficiency can basically cope with most scenes. However, the basic tutorials on the Internet only tell you what lists, dictionaries are and how to use them, and seldom do combination instructions.

Just when collecting prometheus monitoring interface and doing data processing, I used a lot of combination scenes, and listed a few to share.

List (List)

Sequence is the most basic data structure in Python. Each element in the sequence is assigned a number-its position, or index, the first index is 0, the second index is 1, and so on.

List is the most commonly used Python data type and can appear as a comma-separated value within 1 square bracket.

The data items of the list do not need to have the same type

The characteristics are: repeatable and different types

Common ways

To create a list, just enclose different data items separated by commas in square brackets. As shown below:


list1 = ['apple', 'banana', 2008, 2021]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]

###  Toward list Add elements to 
list1.append(3)   ## ['apple', 'banana', 2008, 2021, 3]

###  Use extend Used to connect list
list1.extend([7, 8])  ##['apple', 'banana', 2008, 2021, 3, 7, 8]

### insert  Insert a single element into the list Medium 
list3.insert(2, 'q')   ##['a', 'b', 'q', 'c', 'd']

###  Gets the length of the list 
print(len(list1))   ## 5

###  Traversal list
for name in list1:
    print(name)

extend (extension) and append (append) look similar, but in fact they are completely different.

extend accepts a parameter, which is always an list, and adds each element of this list to the original list. append accepts one parameter, which can be of any data type, and is simply appended to the tail of list.

Dictionary (dictionary)

Dictionary is another variable container model, and can store objects of any type.

The key (key) must be 1-only and can be used as a number, string, or tuple, but not a list The same key appears twice, and the last one will update the value of the previous one.

Common ways

Each key value of the dictionary key=>value Contrast colons : Split, with commas between each key-value pair , Split, the whole dictionary is included in curly braces {} The format is as follows:


>>> dict = {'a': 1, 'b': 2, 'b': '3'}
>>> print(dict)
{'a': 1, 'b': '3'}

###  Access the values in the dictionary 
>>> print(dict['b'])
3

###  Update and add dictionaries 
>>> dict['a'] = 8
>>> dict['c'] = 'cc'
>>> print(dict['a'])
8
>>> print(dict['c'])
cc

###  Delete dictionary elements 
>>> del dict['a']
>>> print(dict)
{'b': '3', 'c': 'cc'}
>>> dict.clear()      #  Empty all entries in the dictionary 
>>> del dict          #  Delete dictionary 

Combined use

Lists can also be nested in lists, and dictionaries can be nested in lists
Dictionaries can be nested in dictionaries, and lists can also be nested in dictionaries
This is very flexible.

List nested list

This is not used much, and it is relatively simple. Look at the example directly:


###  Printout character  5
l = [[1,2],[3,4],[[5,6],[7,8]]]	
>>> print(l[2][0][0])
5

###  Convert a nested list to a non-nested list 
>>> a = [[1,2,3],[4,5,6],[7],[8,9]]
>>> for i in a:
...     t.extend(i)
...
>>> print(t)
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 8, 9]

List nested dictionary

Nesting dictionaries in the list should be the most commonly used way. Give an example directly:


li = [{'a': 1}, {'b': 2}, {'c': 3}]

###(1)  Loop to get every key-value pair in the dictionary :
>>> for i in range(len(li)):
...     for k, v in li[i].items():
...         print(k, v)
...
a 1
b 2
c 3
    
###(2)  Get each key-value pair in the dictionary ( Tuple data type ):
>>> for i in range(len(li)):
...     for j in li[i].items():
...         print(j)
...
('a', 1)
('b', 2)
('c', 3)

###  You can see the 2 The obtained key-value pair is   Tuple data type. 

Dictionary nested dictionary

Dictionary nested dictionary: String as key, dictionary as value:


>>> s={'a':{0:'no',1:{'f':{0: 'no', 1: 'maybe'}}},'b':{}}  # Construction dictionary 
>>> s['a'][0]  #  Value 
'no'
>>> s['a'][1]
{'f': {0: 'no', 1: 'maybe'}}
>>> s['a'][1]['f'][1]  
'maybe'

###  Dictionary nested dictionary 
dict = {
    '192.168.1.1':{'cpu':'0.23',' Memory ':'16',' Hard disk ':'500'},
    '192.168.1.2':{'cpu':'3.22',' Memory ':'64',' Hard disk ':'700'},
    '192.168.1.3':{'cpu':'1.99',' Memory ':'32',' Hard disk ':'800'},
}

### for Traversal 
>>> for k,v in dict.items():
...     print('\n',k,end=': ')
...     for x,y in v.items():
...         print(x,y,end=' ')
...

 192.168.1.1: cpu 0.23  Memory  16  Hard disk  500
 192.168.1.2: cpu 3.22  Memory  64  Hard disk  700
 192.168.1.3: cpu 1.99  Memory  32  Hard disk  800

Dictionary nested list

So how do you nest lists in a dictionary?
Dictionary nested list: string as key, list as value.


###  Dictionary nested list 
dict = {
    ' Fruit ':[' Apple ',' Banana ',' Orange '],
    ' Animals ':[' Lion ',' Tiger ',' Elephant '],
    ' Language ':[' Chinese ',' English ',' Japanese '],
}

###  Access the values in the dictionary 
>>> print(dict[' Fruit '])
[' Apple ', ' Banana ', ' Orange ']

###  Access the value in the list 
>>> print(dict[' Language '][1])
 English 

###  Cyclic printout to see the effect 
>>> for k, v in dict.items():
...     print('\n', k, end=':')
...     for x in v:
...         print(x,end=' ')
...

  Fruit : Apple   Banana   Orange 
  Animals : Lion   Tiger   Elephant 
  Language : Chinese   English   Japanese 

When is nesting used

For example, when you want to store the scores of the top 100 students in grade, because the students are ranked by their scores, the list is an ordered data type, and the dictionary is an unordered data type, so all the data will be stored in the list outside.

For students' grades in various subjects, what they value is not order, but the correspondence between subjects and grades 11, which is the most important thing. In other words, when I want to get the Chinese scores of the 10th classmate, I can directly get the index corresponding to the list and the key corresponding to the dictionary, so that I can get the corresponding value.

As for sorting usage in nesting

References

List: https://www.runoob.com/python/python-lists.html
Dictionary: https://www.runoob.com/python/python-dictionary.html
Nested dictionaries: https://www.pythonf.cn/read/100118 # 1.2 Nested list of dictionaries


Related articles: