current position:Home>Python dictionary usage summary

Python dictionary usage summary

2022-08-06 06:13:38Jing Shenhuo

Some uses of dict dictionary

There are 6 usages

1. ViewThere are two ways:a. dict[key] -> If the key value does not exist, a KeyError will be reported; if the key value exists, the value corresponding to the key will be returned​b. dict.get(key, default) -> If the key does not exist, no error will be reported, and default will be returnedSummary: The dict dictionary looks at the data in the dict according to the key, which is equivalent to looking at the corresponding data according to the index in the list.But dict is unordered, so there is no index, which can only be based on key
2. Add/Modifya method:dict[key] = value -> a. When the key value exists, modify the value corresponding to the keyb. When the key value does not exist, add a key-value pair {key: value}dict[key] = dict.get(key, default)
3. DeleteTwo ways:a.mydict.pop(key)delete key-value pairs in the dictionary according to the key valueb.mydict.popitem()By default delete the last element in the dict dictionary
4. TraversalFour ways:a. Traverse keys -> for key in mydict​Mydict.keys() -> Now encapsulate the keys in the dict dictionary with a listThen traverse -> for key in mydict.keys()​b. Traverse values ​​-> mydict.values() -> encapsulate the values ​​in the dict dictionary with a listThen traverse -> for value in mydict.values​c. Traverse key and values ​​-> mydict.items() -> first encapsulate the key-value pair in dict with tuple, and then put it in listFinally traversing -> for item in mydict.items()
5. Statistics lengthSummarize:len(mydict)Counts the number of key values ​​in the dictionary
6. MembershipSummarize:'sweetheart' in mydict -> falseLook at whether it belongs to key or not, it is the membership relationship between keys

copyright notice
author[Jing Shenhuo],Please bring the original link to reprint, thank you.

Random recommended