Create and use dictionaries
Dictionaries can be created in the following ways:
phoneBook = {"Bill":"1234", "Mike":"4321"}
In a dictionary, keys are unique. If the key is not unique, then the program will not throw an exception, but the same key value will be overwritten by the last one:
phoneBook = {"Bill":"1234", "Mike":"4321", "Bill":"5678"} # If positioned by Bill, the value found is "5678"
dict function
Dictionaries can be built using dick functions through other mappings or sequences of key-value pairs.
items = [["Bill","1234"], ("Mike","4321")] d1 = dict(items) d2 = dict(name = 'Bill', number = '5678', age = 45) print(d1) # {'Bill': '1234', 'Mike': '4321'} print(d2) # {'name': 'Bill', 'number': '5678', 'age': 45}
Basic operation of dictionary
- Many operations of a dictionary are similar to lists:
- len(dict): Returns the number of elements in dictionary Dict
- dict[key]: Returns the value associated with the key
- dict[key] = value: assign a value to key
- del dict[key]: Delete items with keys
- key in dict: Check whether the dict contains items with keys
Dictionary format string (format_map() method)
dic = {'title':'MyTitle', 'url':'http://www.aaa.com', 'company':'Zerobit'} str = """ <html> <head> <title>{title}</title> <head> <body> <h1>{title}</h1> <a href="{url}">{company}</a> </body> </html> """ print(str.format_map(dic))
Iteration of Dictionary
1. Get a list of key s in the dictionary
dic = {'x':1, 'y':2, 'z':3} # Output x y z for key in dic: print(key, end=' ')
2. Get a list of key s and value s in the dictionary at the same time
dic = {'x':1, 'y':2, 'z':3} for key,value in dic.items(): print(key, value)
Dictionary method
clear method
- clear method is used to empty all elements in a dictionary
dic = {'x':1, 'y':2, 'z':3} dic.clear()
copy method and deepcopy function
- The copy method is used to copy a dictionary, which returns the copied new dictionary.
dic = {'x':1, 'y':2, 'z':3} newDic = dic.copy()
The copy method is only a shallow copy, only the dictionary data of the first layer is copied. As for all layers below the second level, both the original dictionary and the new dictionary point to the same value. Whether the elements in the original dictionary are modified or those in the new dictionary, the elements in the original dictionary and the new dictionary will change at the same time.
- If you want to change the above situation, you need to use the deepcopy function in the copy module for deep replication.
from copy import deepcopy dic = {'x':1, 'y':2, 'z':3} newDic = deepcopy(dic)
fromkeys method
- The fromkeys method is used to create new dictionaries based on keys. In the new dictionary, all keys have the same default value.
# Call the fromkeys method on an empty dictionary to create a new dictionary, specifying the key through a list newDic1 = {}.fromkeys(['name', 'company', 'salary']) print(newDic1) # {'name': None, 'company': None, 'salary': None} newDic2 = {}.fromkeys(['name', 'company', 'salary'], 100) print(newDic2) # {'name': 100, 'company': 100, 'salary': 100}
get method
If the key does not exist, the KeyError exception is thrown when the value is obtained from the dictionary in the form of dict[key].
- If you want to avoid key s without throwing exceptions, you need to use the get() method
dic = {'x':1, 'y':2, 'z':3} print(dic.get('a')) # None
items method and keys method
- The items method is used to return all key-value pairs in the dictionary and can be used for iteration.
- The keys method is used to return all keys in the dictionary, as well as to iterate.
pop method and popitem method
- The pop method is used to get the value of the specified key and pop up the key-value pair from the dictionary.
- The popitem method is used to return and pop up the last key-value pair in the dictionary.
For dictionaries, the elements are not in order, so the last key-value pair here refers to the last added key-value pair.
dic = {'c':10, 'a':40, 'b':12, 'x':44} dic['z'] = 3 print(dic.pop('b')) # 12 print(dic.popitem()) # ('z', 3) print(dic) # {'c': 10, 'a': 40, 'x': 44}
setdefault method
- The setdefault method is used to set the default value of the key. This method receives two parameters, the first is key and the second is default. If the key does not exist, the key and default values are added to the dictionary
dic = {} dic.setdefault("name","alex") print(dic) # {'name': 'alex'}
update method
- The update method can update another dictionary with elements in one dictionary.
dic1 = {'c':10, 'a':40, 'b':12, 'x':44} dic2 = {'name': 'Bill', 'number': '5678', 'x': 150} dic1.update(dic2) print(dic1) # {'c': 10, 'a': 40, 'b': 12, 'x': 150, 'name': 'Bill', 'number': '5678'}
If the key-value pair in dict2 does not exist in dict1, a new key-value pair will be added to dict1. If the key already exists in dict1, the value of key in dict1 will be updated with the corresponding value of key in dict2.
values method
- Values method is used to return a list of dictionary median values in iterator form
dic = {'c':10, 'a':40, 'b':12, 'x':44} for val in dic.values(): print(val, end=' ') # 10 40 12 44