I. Dictionary Definition
Dictionary is another variable container model and can store arbitrary types of objects. Each key value pair of a dictionary is separated by a colon (:), and each pair is separated by a comma (,), and the whole dictionary is included in curly brackets ({}). Keys must be unique, but values need not be; values can take any data type, but keys must be immutable data types, such as strings, integers, tuples. Dictionary queries are efficient, and keys are used internally to compute a memory address (hash)
II. Dictionary Operation
1. add
# Create an empty dictionary dict_test = {} dict_test = dict() dict_test["language"] = "Chinese" >>> dict_test {'language': 'Chinese'} # setdefualt() - Default: None dict_test.setdefault("age") >>>{'language': 'Chinese', 'age': None} dict_test.setdefault("name", "WeChat") >>>{'language': 'Chinese', 'age': None, 'name': 'WeChat'}
2. amendment
dict_test = {'language': 'Chinese', 'age': None, 'name': 'WeChat'} dict_test["age"] = 18 >>>{'language': 'Chinese', 'age': 18, 'name': 'WeChat'} # update() - Equivalent to merging two dict s dict_one = {"name":"tree", "age":100, "height":"90M"} dict_two = {"name":"tree", "color":"green"} dict_one.update(dict_two) >>>dict_one {'name': 'tree', 'age': 100, 'height': '90M', 'color': 'green'}
3. query
dict_test = {'language': 'Chinese', 'age': 10, 'name': 'WeChat'} (1) direct key take - When key When it does not exist, KeyError dict_test["age1"] (2) get() Method dict_test.get("name") dict_test.get("name_new") ->No key,Return None dict_test.get("name_new", "Non-existent") ->No key,Specify the return value (3) setdefault() -Added: First see if there are any. key,Return its value if you have it; no, add new execution dict_test.setdefault("name", "QQ") >>>name stay dict_test In the middle, the corresponding value is returned, and in the absence, the corresponding value is returned. QQ
4. delete
dict_test = {'language': 'Chinese', 'age': 10, 'name': 'WeChat'} (1) dict_test.pop("age") ->pop Appoint key Delete, return value >>>{'language': 'Chinese', 'name': 'WeChat'} (2) dict_test.popitem() ->Random deletion (3) del dict_test["name"] (4) dict_test.clear() ->empty
III. Dictionary Method
1. items()
# This type is dict_items type, which can be iterated. item = dic.items() print(item,type(item)) >>>dict_items([('name', 'jin'), ('sex', 'male'), ('age', 18)]) <class 'dict_items'>
2. keys()
keys = dic.keys() print(keys,type(keys)) >>>dict_keys(['sex', 'age', 'name']) <class 'dict_keys'>
3. values()
values = dic.values() print(values,type(values)) >>>dict_values(['male', 18, 'jin']) <class 'dict_values'> Ditto
4. iteration
1. Default cyclic dictionary key key for key in dic: print(key) 2. Cyclic dictionary key key for key in dic.keys(): print(key) 3. Values in Circulating Dictionary for value in dic.values(): print(value) 4. Key-value pairs in cyclic Dictionaries for key, value in dic.items( ): print(key, value) len() Calculate the number of key-value pairs
IV. Circular deletion of dictionaries
1. Delete people with numbers less than 100 dic = {'alex':100, 'wusir':20000, 'jack':12, 'tony':1, 'ketty': 3000} # First create a new list to store the people you want to delete li = [] # Key value pairs in circular dictionary for key, value in dic.items(): # People less than 100 are added to the list if value < 100: li.append(key) # Remove keys from dictionaries by iterating through the elements in the list for el in li: del dic[el] print(dic) //Result: {'alex': 100, 'wusir': 20000, 'ketty': 3000}
5. fromkeys()
1. It's not about changing dictionaries. It's a class approach. It's about creating new dictionaries. dic = {} dic_new = dic.fromkeys("abc", "hello") print(dic) # {} print(dic_new) # {'a': 'hello', 'b': 'hello', 'c': 'hello'}
2. The new dictionary is created by iterating the first parameter and forming key-value pairs with the second parameter. fromkeys( )Normally, class names are accessed. dic1 = dic.fromkeys(['a', 'b'], []) dic1['a'].append('alex') # The same value used by key >>>{'a':['alex'], 'b':['alex']}
1. The same key is not allowed to appear twice. When created, if the same key is assigned twice, the latter value will be remembered. 2. Keys must be immutable, so you can use numbers, strings or tuples instead of lists. 3. immutable data (not hash) (3): Number (number), String (string), Tuple (tuple); 4. Variable data (hash) (3): List (list), Dictionary (dictionary), Set (collection).
Six. Example
With the following value li= [11,22,33,44,55,66,77,88,99,90], all values greater than 66 are saved in the first key of the dictionary and values less than 66 are saved in the second key. That is: {k1': list of all values greater than 66,'k2': list of all values less than 66}
1. method 1
li= [11,22,33,44,55,66,77,88,99,90] result = {} for el in li: if el < 66: # setdefault can help us to add new keys, but if keys exist, they will not be added. # {'key1':[11,22]} result.setdefault("key1", []).append(el) else: result.setdefault("key2", []).append(el)
2. method two
li= [11,22,33,44,55,66,77,88,99,90] result = {} for el in li: if el < 66: # 11, 22 if result.get("key1") == None: result["key1"] = [el] # 11 else: result['key1'].append(el) else: if result.get("key2") == None: result["key2"] = [el] # 11 else: result['key2'].append(el)