A dictionary is another variable container model and can store any type of object.
Each key value (Key=>value) pair of the dictionary is separated by a colon (:), separated by commas (,), and the entire dictionary is enclosed in curly braces ({}) ;
The dictionary value can be used without restrictions on any Python object, either a standard object or a user-defined one, but the key is not available, and if the same key is assigned two times, the latter value will be remembered.
Values can take any data type, but the key must be immutable, such as a string, a number, or a tuple (a mutable type such as a list cannot be a key).
Create, Access:
Dict = {' Name ': ' Zara ', ' age ': 7, ' Class ': ' A ';
Dict2 = { };//Empty dictionary
print "dict[' name ']:", dict[' name '];
Print "dict[' age ']:", dict[' age ';
The dictionary contains the list: dict={' yangrong ': ['], ' IT ', ' Xiaohei ': ['], ' DotA ']}
Dictionary contains dictionary: dict={' yangrong ': {"age": "The", "Job": "IT"}, "Xiaohei": {"' Age ': '", ' job ': ' DotA '}}
Modify, add:
dict[' age ' = 8; # Update existing entry
dict[' School ' = ' DPS School '; # ADD new entry
Delete:
Del dict[' Name ']; # The DELETE key is the ' Name ' entry
dict.clear (); # Empty dictionary All entries
del dict; # Delete Dictionary
To see if a specific key is included: Dict.has_key (k)
Returns False if the key returns true in the dictionary Dict
view all keys, values, (key, value) pairs: Dict.keys (), Dict.values (), Dict.items (), return value type as List
Traverse:
For d,x in Dict.items ():
print ' key: ' +d+ ', Value: ' +x
For k in Dict.keys ():
Print "Key:" +k+ ", Value:" +dict[k]
Sort:
# sorted by Key
Print sorted (Dict1.items (), Key=lambda d:d[0])
Or:
Sorted (D.items (), Lambda X, y:cmp (x[0), y[0)), or reverse order:
Sorted (D.items (), Lambda X, y:cmp (x[0), y[0), reverse=true) # sorted by value
Print sorted (Dict1.items (), Key=lambda d:d[1])
Or:
Sorted (D.items (), Lambda X, y:cmp (x[1), y[1)), or reverse order:
Sorted (D.items (), Lambda X, y:cmp (x[1), y[1), reverse=true)
List
Accessing elements by distance difference
Sequential access, slow speed
Small storage space Requirements
Dict
Accessing elements by index
Need large space, but visit soon
Set
Elements cannot be duplicated
Other and dict are basically similar
|, & 、-、 ^, respectively: And, pay, poor, deficit