Python dictionaries can store any type of object, such as strings, numbers, tuples ... Advantages: Easy to take value, fast speed
1, create a dictionary
A dictionary consists of a key (key) and a corresponding value (value). Dictionaries are also referred to as associative arrays or hash tables. The basic syntax is as follows:
Dict = {' Alice ': ' 2341 ', ' Beth ': ' 9102 ', ' Cecil ': ' 3258 '}
Attention:
Each key and value is separated by a colon (:), each pair is comma-delimited, each pair is separated by commas, and the whole is placed in curly braces ({}).
The key must be unique, but the value does not have to be.
The value can take any data type, but it must be immutable, such as a string, number, or tuple.
2, accessing the values in the dictionary
Print (d[' key ') if you write a value that does not exist, you will get an error.
Print (D.get (' key ')) if you write a value that does not exist, return none
Print (D.get (' key ', ' not find ')) returns "Not find" if no value exists
Print (D.keys ()) #获取所有的key value
Print (D.values ()) #获取所有的value value
If ' key ' in D: #判断key是否存在
Print (' key ')
For k,v in D.items (): #遍历字典
Print (K,V)
No need to convert to list format, preserving the original character of the dictionary
For K in Dict:
Print (K,dict[k])
Print (K,dict.get (k)) value fast, good performance
3, modify the dictionary
d[' key ' = value key exists as modified, key does not exist that is new
D.setdefault (' key ', value) can only be added
4. Delete the dictionary element
D.pop (' key ') must be passed because the dictionary is unordered
D.popitem () randomly deletes a
D.clear () Empty Dictionary
5, other
Print (Dict.items ()) output a list format (not a list in the real sense)
Print (List (Dict.items ())) turns the dictionary key and value into a multidimensional list
Output Result:
len
(
dict
):计算字典元素个数,即键的总数。
str
(
dict
):输出字典可打印的字符串。
type
(variable):返回输入的变量类型,如果变量是字典就返回字典类型。
A summary of common methods for Python dictionaries