() Creating a Dictionary
Copy Code The code is as follows.
>>> fdict = dict((['x', 1], ['y', 2]))
>>> fdict
{'y': 2, 'x': 1}
() to create a "default" dictionary whose elements have the same value
Copy Code The code is as follows.
>>> ddict = {}.fromkeys(('x', 'y'), -1)
>>> ddict
{'y': -1, 'x': -1}
3. Iterate over the dictionary
Iterating with keys()
Copy Code The code is as follows.
>>> dict2 = {'name': 'earth', 'port': 80}
>>>
>>>> for key in ():
... print 'key=%s, value=%s' % (key, dict2[key])
...
key=name, value=earth
key=port, value=80
Iterating with Iterators
Copy Code The code is as follows.
>>> dict2 = {'name': 'earth', 'port': 80}
>>>
>>>> for key in dict2:
... print 'key=%s, value=%s' % (key, dict2[key])
...
key=name, value=earth
key=port, value=80
4. Get the value
Dictionary keys with center brackets to get
Copy Code The code is as follows.
>>> dict2['name']
'earth'
5. Member operator: in or not in
Determine if a key exists
Copy Code The code is as follows.
>>> 'server' in dict2 # or dict2.has_key('server')
False
6. Update dictionary
Copy Code The code is as follows.
>>> dict2['name'] = 'venus' # update existing entries
>>> dict2['port'] = 6969 # update existing entries
>>> dict2['arch'] = 'sunos5' # add new entry
7. Delete Dictionary
Copy Code The code is as follows.
del dict2['name'] #Delete the entry with the key "name".
() # Delete all entries in dict2
del dict2 #delete the entire dict2 dictionary
('name') #Delete and return the entry with the key "name".
(return value list
Copy Code The code is as follows.
>>>
>>> ()
[80, 'earth']
() Returns a list of (key, value) tuples.
Copy Code The code is as follows.
>>> ()
[('port', 80), ('name', 'earth')]