1. Creating and Using dictionaries
1) format of the dictionary:
Phonebook = {' Alice ': ' 1234 ', ' Beth ': ' 1920x1080 ', ' Cecil ': ' 4537 '}
The ====== dictionary consists of two curly braces, separated by a colon: between the key and the value, separated by commas.
2) Create a dictionary--dict function:
Dict (), New Empty dictionary.
>>> items = [(' Name ', ' Sandy '), (' age ', 38)]
>>> d = dict (items)
>>> D
{' Age ': $, ' name ': ' Sandy '}
>>> d[' name ']
' Sandy '
>>>
>>> Dict ()
{}
>>> dict (name= ' Sandy ', age=42)
{' Age ':, ' name ': ' Sandy '}
>>> Dict (sandy=38,alice=32)
{' Alice ': +, ' Sandy ': 38}
>>>
3) Basic operation of the dictionary
Len (d)---Returns the number of items in the dictionary;
D[K]---Returns the value of the key k;
D[K]=V---Associates the value to the key k;
Del D[k]---Delete the key to K;
K in d---check D for items with key K
2. Dictionary method
| Method |
Role |
return value |
Use |
| Clear |
Clears all items in the dictionary |
None (no return value) |
D.clear () |
| Copy |
Copy Dictionary |
Returns a new dictionary with the same item |
X=d.copy () |
| Fromkeys |
Creates a new dictionary with the given key, with the default corresponding value of None for each key |
A new dictionary? |
|
| Get |
Access to a dictionary item by key is more lenient than direct access (such as d[' name '), which returns none when attempting to access a nonexistent item |
Value or None |
D.get (' name ') |
| Has_key |
Check if the dictionary contains the given key, which is the equivalent of K in D |
True or False |
D.haskey (k) |
| Items and Iteritems |
Items returns a list of all items in the dictionary |
List |
D.items () |
| Keys and Iterkeys |
The Keys method returns the key of the dictionary as a list |
List |
D.key () |
| Pop |
Gets the value corresponding to the given key and removes the key-value from the dictionary |
Value |
D.pop () |
| Values |
Returns the value of the dictionary as a list |
List |
D.values () |
| SetDefault |
Gets the value associated with the given key and, if the key does not exist, sets the key and the default value (given or none) in the dictionary |
Value or key-value |
D.setdefault (' name ', ' N/A ') |
| Update |
Update another dictionary with one dictionary item |
Updated dictionaries |
D.update (x) |
A Dictionary of Python learning