This article mainly introduces how to use dict (dictionary) in python3. It provides a detailed list of functions, which has some reference value for everyone. let's take a look at it. This article mainly introduces how to use dict (dictionary) in python3. It provides a detailed list of functions, which has some reference value for everyone. let's take a look at it.
1. clear (clear dictionary content)
Stu = {'num1': 'Tom ', 'num2': 'Lucy', 'num3': 'Sam ',} print (stu. clear () # output: None
II. copy (copy dictionary)
stu = { 'num1':'Tom', 'num2':'Lucy', 'num3':'Sam',}stu2 = stu.copy()print(stu2)
3. fromkeys (specify a list and use the values in the list as the dictionary key to generate a dictionary)
Name = ['Tom ', 'Lucy', 'Sam '] print (dict. fromkeys (name) print (dict. fromkeys (name, 25) # specify the default value # output: {'Tom ': None, 'Lucy': None, 'Sam ': None} # {'Tom': 25, 'Lucy ': 25, 'Sam': 25}
4. get (specify the key to obtain the corresponding value)
Stu = {'num1': 'Tom ', 'num2': 'Lucy', 'num3': 'Sam ',} print (stu. get ('num2') # output: Lucy
5. items (return the list of elements composed of key-value pairs)
Stu = {'num1': 'Tom ', 'num2': 'Lucy', 'num3': 'Sam ',} print (stu. items () # output: dict_items ([('num2', 'Lucy '), ('num3', 'Sam'), ('num1 ', 'Tom ')])
6. keys)
Stu = {'num1': 'Tom ', 'num2': 'Lucy', 'num3': 'Sam ',} print (stu. keys () # output: dict_keys (['num3', 'num1', 'num2'])
VII. pop (obtain the value of the specified key and delete it in the dictionary)
Stu = {'num1': 'Tom ', 'num2': 'Lucy', 'num3': 'Sam ',} name = stu. pop ('num2') print (name, stu) # output: Lucy {'num1': 'Tom ', 'num3': 'Sam '}
8. popitem (obtain a random key-value pair and delete it in the dictionary)
Stu = {'num1': 'Tom ', 'num2': 'Lucy', 'num3': 'Sam ',} name = stu. popitem () print (name, stu) # output: ('num2', 'Lucy ') {'num3': 'Sam', 'num1': 'Tom '}
9. setdefault (obtain the value of the specified key. if the key does not exist, it is created)
Stu = {'num1': 'Tom ', 'num2': 'Lucy', 'num3': 'Sam ',} name = stu. setdefault ('num5') print (name, stu) # output: None {'num1': 'Tom ', 'num2': 'Lucy', 'num5': None, 'num3': 'Sam '}
10. update (add a key-value pair to the dictionary)
Stu = {'num1': 'Tom ', 'num2': 'Lucy', 'num3': 'Sam ',} stu. update ({'num4': 'Ben'}) print (stu) # output: {'num2': 'Lucy ', 'num3': 'Sam', 'num1 ': 'Tom ', 'num4': 'Ben '}
The above describes how to use the dict dictionary in python3. For more information, see other related articles in the first PHP community!