Basic use of Python dictionaries and collections

Posted by Roo on Sun, 16 Jan 2022 22:43:57 +0100

Basic usage and methods of dictionary

1, Definition of dictionary

(1) Dictionary: use {} to identify
(2) The structure of the dictionary is to treat it as a collection of {key:value}, key:value pairs,
(3) It contains two elements separated by ",". Each element is composed of key and value, with ":" in the middle
(4) Keys in the same dictionary are unique (duplicate key s are not allowed)
(5) The key in the dictionary can only be immutable data (numeric value, string, tuple), usually using string;
(6) When the same key exists, no error will be reported, but only the last key will be output
(7) Value: the value in the dictionary can hold any type of data
(8) Empty dictionary: {}

2, How dictionaries are defined

Method 1: use ":"

dic = {'name': 'Carefree', 'age': 18}

Method 2: do not use ":"

dic = dict(name = 'Carefree',
           age = 18,
           name1 = 'Sunflower')
print(dic)

Running result: {name ':'xiaoyao', 'age': 18, 'name1':'Sunflower '}

Method 3: quickly convert multiple tuples into a dictionary

dic = dict(
    [('name','Carefree'),('age',18),('name1','Sunflower')]
)
print(dic)

Running result: {name ':'xiaoyao', 'age': 18, 'name1':'Sunflower '}

3, Operation method of Dictionary (addition, deletion, query and modification)

1. Add operation: assign value directly through key

dic = {'name':'xiaoyao','name1':'cmq','name2':'FENG'}
dic['name3'] = 'Xiaobai'
print(dic)

Running result: {Name:'xiaoyao ',' name1 ':'cmq', 'name2':'FENG ',' name3 ':'xiaobai'}

Note:

1) String, list, tuple, support subscript operation, subscript value and slice
2) The dictionary does not support subscript values and slicing

2. Modification operation: assign value directly through key

# If there is no increase, it will be changed; Dictionaries are out of order
dic = {'name':'xiaoyao','name1':'cmq','name2':'FENG'}
dic['name'] = 'woman'
print(dic)

Running result: {Name:'woman ','name1':'cmq ','name2':'FENG '}

3. Query operation

Method 1: get the key directly. If the key does not exist, keyerror will be reported

dic = {'name':'xiaoyao','name1':'cmq','name2':'FENG'}
print(dic['name'])

Running result: xiaoyao

dic = {'name':'xiaoyao','name1':'cmq','name2':'FENG'}
print(dic['111'])

Operation result: keyerror: '111' (get the value through the key, and no key error is reported)

Method 2: get directly through the key. If the key does not exist, return None (None: empty)

dic = {'name':'xiaoyao','name1':'cmq','name2':'FENG'}
print(dic.get('name'))

Running result: xiaoyao

dic = {'name':'xiaoyao','name1':'cmq','name2':'FENG'}
print(dic.get('111'))

Run result: None

4. Delete operation

Method 1: pop deletes the corresponding key value pair through the specified key

dic = {'name':'xiaoyao','name1':'cmq','name2':'FENG'}
dic.pop('name')
print(dic)

Operation result: {name1 ':'cmq','name2 ':'FENG'}

Method 2: popitem deletes the last added key value pair (python before 3.5 is random)

dic = {'name':'xiaoyao','name1':'cmq','name2':'FENG'}
print(dic.popitem())
print(dic)

Operation result: ('name2', 'FENG')
{'name': 'xiaoyao', 'name1': 'cmq'}

Method 3: delete the del keyword

dic={'ee':14,"jj":22,"kk":33}
del dic['jj']
print(dic)

Operation result: {ee ': 14,' kk ': 33}

Method 4: clear the dictionary

dic = {'name':'xiaoyao','name1':'cmq','name2':'FENG'}
dic.clear()
print(dic)

Run result: {}

4, Other methods of dictionary

1. Keys (): get all the keys in the dictionary

# dict_keys is the data type in the dictionary, not the data type commonly used in python. It can be converted into a list and printed
dic = {'name':"Carefree",'age':18,'sex':"male"}
res1 = dic.keys()
print(res1)
print(list(res1))

Running result: dict_keys([‘name’, ‘age’, ‘sex’])
['name', 'age', 'sex']

2. Values (): get all the values in the dictionary

dic = {'name':"Carefree",'age':18,'sex':"male"}
res2 = dic.values()
print(list(res2))

Operation result: [Xiaoyao, 18, 'male']

3. items (): often used to: get the key value pairs of the dictionary (each key value pair will be converted into a tuple)

"""
The generated data type is list nested tuples, and each tuple is a key value pair of the dictionary,
The key of the dictionary is the first element of the tuple, and the value of the dictionary is the second element of the tuple;
"""
dic = {'name':"Carefree",'age':18,'sex':"male"}
res3 = dic.items()
print(list(res3))

Running result: [('name ',' carefree '), ('age', 18), ('sex ',' male ')]

4. update (): add multiple key value pairs to the dictionary (add one dictionary to another)

"""
1,If there are duplicate keys in the dictionary, the last one will overwrite the first one
2,If not, increase and change
3,The method is similar to extend Method to add multiple elements to the list
"""
dic = {'name':"Carefree",'age':18,'sex':"male"}
dic.update({'aa':11,'bb':22,'cc':22})
print(dic)

Running result: {name ':' carefree ',' age ': 18,' sex ':' male ',' aa ': 11,' bb ': 22,' cc ': 22}

Basic use of collections

1, Definition of set

Definition: curly braces or set() function can be used to create a set.
The data in the collection can only be immutable types: numeric string tuples (other types will report errors)
Note: to create an empty set, you can only have set() instead of {}, because the latter is to create an empty dictionary

2, Method of collection

1) Add element: add

set2 = {11,22}
set2.add(999)
set2.add(100)
print(set2)

Running result: {11, 100, 22, 999}

2) Delete element: remove

set2 = {11,22}
set2.remove(11)
print(set2)

Run result: {22}

3, Properties of sets

1) The elements in the collection are unordered

# The printed content is different from the definition. There is no order, and "slice" and "index value" cannot be used
set2 = {11,2222,33,3333,'aa','bb','Carefree'}
print(set2)

Operation results: {33, 3333, 'Xiaoyao', 11, 'aa', 2222, 'bb'}

2) Elements in a set cannot be repeated (the same as a set in Mathematics)

# After running, only one of the same elements will be retained
set2 = {11,11,2222,33,3333,11,22,33,11,22,22,'aa','bb','Carefree'}
print(set2)

Operation results: {33, 3333, 11, 2222, 'Xiaoyao', 'aa', 22, 'bb'}

#Collections and dictionaries are out of order
# hash algorithm is encrypted and stored according to the corresponding rules
# A dictionary is a hash of key s
# In the set, the data in the set is hash ed directly
# Only data of immutable type can be hash ed

4, Usage of collection properties

Quickly remove duplicate elements from the list

# A collection removes duplicate elements from a list
li1=[11,222,11,22,11,222,33]
print("customary li1:")
print(li1)

# 1. First convert the list to a set
s=set(li1)
print("1.First convert the list to a collection:")
print(s)

# 2. Then convert the set to a list
li2=list(s)
print("2.Then convert the set to a list:")
print(li2)

Operation results:
Original li1:
[11, 222, 11, 22, 11, 222, 33]
1. First convert the list to a set:
{33, 11, 222, 22}
2. Then convert the set to a list:
[33, 11, 222, 22]

Data type summary

1. Classification by data structure
(1) Numeric type: integer floating point Boolean
(2) Sequence type: String List tuple
(3) Hash type: Dictionary collection
2. Immutability of data type
Immutable type: numeric type string tuple
After the string and tuple are defined, the internal structure or value cannot be modified (the value in the internal unit is of immutable type)
Variable types: list, dictionary, set
How to distinguish between variable and immutable types: define a set and put the data into the set to see that there will be no error
1. Print error is a variable type;
2. Printing without error is an immutable type;
3. Only immutable type data can exist in the collection;

set1 = {[1,2,3],[1,2]}               # List in collection
print(set1)

Running result: TypeError: unhashable type: 'list'

set2 = {{'Name':'Carefree'},{'Age':18}}    # Dictionary in collection
print(set2)

Running result: TypeError: unhashable type: 'dict'

set3 = {{1,2,3},{1,2}}               # Collection is a collection
print(set3)

Running result: TypeError: unhashable type: 'set'

set4 = {1,2,3,4,5}                  # Values in the set
print(set4)
set5 = {'sdda','asddd','ssaaa'}        # String in collection
print(set5)
set6 = {(1,2,3),(1,2,3,4)}           # Tuple in collection
print(set6)

Operation result: {1, 2, 3, 4, 5}
{'asddd', 'sdda', 'ssaaa'}
{(1, 2, 3, 4), (1, 2, 3)}

Topics: Python Back-end