Unlike tuples, dictionaries are a "mutable" object type, which means that the elements contained within them can be changed at will.
As you've already seen, adding a new element to a dictionary is as simple as assigning a value to a key.
>>> characters = {"new hope":"Luke", "teacher":"Yoda", "bad guy":"Darth"}
>>> characters["princess"] = "Leia"
>>> characters["worse guy"] = "The Emperor"
>>> characters
{'princess': 'Leia', 'teacher': 'Yoda', 'new hope': 'Luke', 'bad guy':
'Darth',
'worse guy': 'The Emperor'}
>>>
You can also use this technique to update existing dictionary
elements with new values,
>>> characters["teacher"] = "Obi-Wan"
>>> characters
{'princess': 'Leia', 'teacher': 'Obi-Wan', 'new hope': 'Luke', 'bad guy':
'Darth', 'worse guy': 'The Emperor'}
>>>
or use the del() method to remove individual key-value pairs
from the dictionary.
>>> del (characters["worse guy"])
>>> characters
{'princess': 'Leia', 'teacher': 'Obi-Wan', 'new hope': 'Luke', 'bad guy':
'Darth'}
>>>
A built-in update() method makes it possible to copy elements
from one dictionary to another.
>>> charactersCopy = {}
>>> charactersCopy.update(characters)
>>> charactersCopy
{'teacher': 'Obi-Wan', 'princess': 'Leia', 'new hope': 'Luke', 'bad guy':
'Darth'}
>>>
while a clear() method allows you to empty the container of
all elements,
>>> charactersCopy.clear()
>>> charactersCopy
{}
>>>
The built-in len() function can be used to calculate the
number of key-value pairs in a dictionary.
>>> characters
{'princess': 'Leia', 'teacher': 'Obi-Wan', 'new hope': 'Luke', 'bad guy':
'Darth'}
>>> len (characters)
4
>>>
It should be noted at this point that dictionaries do not
support concatenation or repetition, and, since they don't use numerical indices, it's not possible to extract slices of a dictionary either. In fact, attempting this will cause Python to barf all over your screen,
>>> characters
{'princess': 'Leia', 'teacher': 'Obi-Wan', 'new hope': 'Luke', 'bad guy':
'Darth'}
>>> opposites
{'day': 'night', 'white': 'black', 'yes': 'no'}
>>> newDict = characters + opposites
Traceback (innermost last):
File "", line 1, in ?
TypeError: bad operand type(s) for +
>>>
as will the deadly sin of trying to access a key which
doesn't exist.
>>> characters
{'princess': 'Leia', 'teacher': 'Obi-Wan', 'new hope': 'Luke', 'bad guy':
'Darth'}
>>> characters["robot"]
Traceback (innermost last):
File "", line 1, in ?
KeyError: robot
>>>
As a matter of fact, you can use the has_key() built-in
method to check whether or not a particular key exists, thereby making it easier to avoid errors like the one above.
>>> characters
{'princess': 'Leia', 'teacher': 'Obi-Wan', 'new hope': 'Luke', 'bad guy':
'Darth'}
>>> characters.has_key("teacher")
1
>>> characters.has_key("princess")
1
>>> characters.has_key("robot")
0
>>>
Please enable JavaScript to view the comments powered by Disqus. blog comments powered by