Seventh chapter mapping and aggregation capabilities
A dictionary (the only mapping type in Python)
1 basic
Create and assign values:
Normal creation: >>>dict = {' name ': ' Earth ', ' Port ': 80}
Use the Factory function Dict () to create:
>>> fdict = Dict ([' X ', 1], [' Y ', 2])
>>> fdict
{' Y ': 2, ' X ': 1}
Use Fromkeys () to create a default dictionary:
>>> ddict = {}.fromkeys (' x ', ' Y '),-1)
>>> ddict
{' Y ':-1, ' X ':-1}
>>> edict = {}.fromkeys (' foo ', ' Bar ')
>>> Edict
{' Foo ': None, ' Bar ': none}
To access the values in the dictionary:
dict[' name ']
>>>> for key in Dict2. Keys():
... print ' key=%s, value=%s '% (key, Dict2[key])
>>>> for key in Dict2:
... print ' key=%s, value=%s '% (key, Dict2[key])
Has_key () and in, not to determine if a key is in the dictionary
To delete a dictionary element and dictionary:
Del dict[' name ']
Dict.clear ()
Del Dict
Dict.pop (' name ') deletes and returns an entry with the key ' name '
2 operator
Python core Programming Read Pen 5: Mappings and collection types