PythonDictionary
A dictionary is another mutable container model and can store any type of object.
Each key value of the dictionary (Key=>value) is split with a colon (:), each pair is separated by a comma (,), and the entire dictionary is enclosed in curly braces ({}) , as shown in the following format:
D = {key1:value1, key2:value2}
The key must be unique, but the value does not have to be.
The value can take any data type, but the key must be immutable, such as a string, a number, or a tuple.
A simple Dictionary instance:
Dict = {' Alice ': ' 2341 ', ' Beth ': ' 9102 ', ' Cecil ': ' 3258 '}
You can also create a dictionary like this:
Dict1 = {' abc ': 456}dict2 = {' abc ': 123, 98.6:37}
dict1={} #建立一个空字典
>>> type (DICT1)
< type ' Dict ' >
Add python dictionary elements: two methods
#第一种 >>> dict1[' a ']=1>>> dict1 {' A ': 1} #第二种: SetDefault method >>> Dict1.setdefault (' B ', 2) 2 >>> Dict1
Delete a Python dictionary
#删除指定键-value pairs >>> dict1 {' A ': 1, ' B ': 2} >>> del dict1[' a '] #也可以用pop方法, Dict1.pop (' a ') >>> dict1 {' B ': 2} #清空字典 >>> dict1.clear () >>> dict1 #字典变为空了 {} #删除字典对象 >>> del dict1 >>> dict1 Traceback (most recent call last):
Accessing values in the dictionary
Put the corresponding key into square brackets, as follows:
Dict = {' name ': ' Zara ', ' age ': 7, ' Class ': ' First '} print ("dict[' name ']:", dict[' name ']) print ("dict[' age ']:", dict [' Age '])
#以上实例输出结果:
Dict[' Name ']: Zaradict[' age ']:7
If the data is accessed using a key that is not in the dictionary, the output error is as follows:
#!/usr/bin/python dict = {' Name ': ' Zara ', ' age ': 7, ' Class ': ' First '} print ("dict[' Alice '):", dict[' Alice ') The above example output: dict[' Zara ']:traceback (most recent call last): File "test.py", line 4, in <module> print "Dict [' Alice ']: ", dict[' Alice '); Keyerror: ' Alice '
Modify Dictionary
The way to add new content to a dictionary is to add a new key/value pair, modify or delete an existing key/value pair as follows:
#!/usr/bin/python dict = {' Name ': ' Zara ', ' age ': 7, ' Class ': ' First '} dict[' age '] = 8; # Update existing Entrydict [' School '] = "DPS School"; # ADD new entry print ("dict[' age ']:", dict[' [age ']) print ("dict[' School ']:", dict[' School ']) above instance output: dict[' aged ']: 8dict[' School ']: DPS School
Delete a dictionary element
The ability to delete a single element also clears the dictionary, emptying only one operation.
Show Delete a dictionary with the Del command, as in the following example:
#!/usr/bin/python#-*-coding:utf-8-*-dict = {' name ': ' Zara ', ' age ': 7, ' Class ': ' First '} del dict[' Name '] # Delete key is ' N ' Ame ' entry dict.clear () # Empty dictionary all Entries del dict # Delete dictionary print ("dict[' age '):", dict[' age ') print ("dict[' School '): ", dict[' School ')" but this throws an exception because the dictionary no longer exists after Del: dict[' age ']:traceback (most recent call last): File "test.py", line 8, in <module> print "dict[' age '):", dict[' age '); TypeError: ' Type ' object is unsubscriptable
Properties of Dictionary Keys
A dictionary value can take any Python object without restriction, either as a standard object or as a user-defined one, but not a key.
Two important points to keep in mind:
1) The same key is not allowed to appear two times. When created, if the same key is assigned a value of two times, the latter value is remembered, as in the following example:
#!/usr/bin/python dict = {' name ': ' Zara ', ' age ': 7, ' name ': ' Manni '} print ("dict[' name ']:", dict[' name ']) Above instance output: dict[' Name ']: Manni
2) The key must be immutable, so it can be used as a number, string or tuple, so the list is not, the following example:
#!/usr/bin/python dict = {[' name ']: ' Zara ', ' Age ': 7} Print ("dict[' name ']:", dict[' name ']) above instance output: Traceback (most recent): File "test.py", line 3, <module> dict = {[' Name ']: ' Zara ', ' Age ': 7}; Typeerror:list Objects is unhashable
Dictionary built-in functions & methods
The Python dictionary contains the following built-in functions: CMP (DICT1, DICT2) compares two dictionary elements. Len (dict) calculates the number of dictionary elements, that is, the total number of keys. The STR (dict) output dictionary is a printable string representation. Type (variable) returns the type of the variable entered, if the variable is a dictionary. The Python dictionary contains the following built-in methods: Radiansdict.clear () removes all elements in the dictionary radiansdict.copy () returns a dictionary of shallow copy Radiansdict.fromkeys () to create a new dictionary, The key that is the dictionary of the elements in the sequence seq, Val is the initial value of the dictionary for all Keys Radiansdict.get (key, Default=none) returns the value of the specified key, if the value does not return the default value in the dictionary Radiansdict.has_key ( Key) returns Falseradiansdict.items () returns a Dict (key, value) tuple array Radiansdict.keys () in the list if the key returns true in the dictionary. Returns a dictionary with a list all keys Radiansdict.setdefault (key, Default=none) and get () are similar, but if the key does not exist in the dictionary, the key is added and the value is set to Defaultradiansdict.update ( DICT2) Update the key/value pairs of the dictionary dict2 to Dict radiansdict.values () returns all values in the dictionary as a list
Python---dict dictionary