Dictionary
1. Dictionary creation
? Assignment Creation Dictionary
? Create a dictionary from the factory function
# Assignment Creation Dictionary , Key-value, Key- value pair
# Create a dictionary from the factory function
# Create a dictionary using the fromkeys method of the dictionary , with a default value for all elements ;
# If no default value is specified , the default is none;
# Set the default value for each element to "pay ";
2.characteristics of analytic dictionaries ( compared with tuples and lists )
? dictionaries cannot be indexed and sliced , because the dictionary is an unordered data type ;
? dictionaries do not support duplicates and connections ;
? Dictionary support member operators : Judging the dictionary Key whether the value exists in the dictionary ; in, not in
3, the dictionary additions and deletions to search
Increase
Dictionary name [Key] = value
D.update (A=1, b=2)
D.update ({' A ': 1, ' B ', 2})
D.setdefault (' A ', 1)
* * Highlights : differences between SetDefault and The update method
# add key-value to the dictionary by using the dictionary name [Key]=value ]
# Update method implementation added : Key exists , overwriting value , otherwise , Add
It is more recommended that the following method
# SetDefault Implementation Add :
Key exists , overwriting value values ; otherwise , Add
Change
Dictionary name [Key]=value
D.update ({' A ': 2, ' B ': 3})
D.update (a=2, b=3)
Check
View key value ;
View value values ;
View key-value key value pairs ;
See if key exists ;
Services = {' FTP ': $, ' http ': [80, 8080]}
# View key value
Services.keys ()
Services.viewkeys () # give the key a name
Services.iterkeys ()
# View value Values
# View key-value key value pairs
# See if key exists
# View the value values corresponding to the specified key ;
if key does not exist , do not error ; If there is , return value value .
By deleting
--D.pop (key) deletes the dictionary element for the specified key ;
--D.popitem () randomly deletes the key-value element of the dictionary ;
-Del D[key] delete The dictionary element for the specified key ;
--D.clear () Empty the dictionary element
4. Iterate through the dictionary
# iterates through the dictionary's key and value values by default
# The key value of the dictionary is traversed by default
5. Dictionary Application
application 1: implement case statements through a dictionary
? currently Python does not support case statements ;
? Two ways to implement a case statement :
? if...elif...elif...else ...
? Dictionary implementation
# If: Elif. Elif. Implement
# Dictionary Implementation case Statement
python--Dictionary