Lesson 7
Objects and Dictionaries
Chapter 4: Dictionaries
More dictionary methods
We have explored the following dict
methods so far:
.get()
.keys()
.values()
.items()
There are several more dict
methods listed in the official documentation.
Some of these are similar to list
methods (.clear()
, .pop()
) so we will not discuss these, but feel free to play around with these yourself.
Here are two more methods that is specific to dict
.
update()
The .update()
method is like list
‘s .extend()
, where you can concatenate another dict
, or a list
of 2-tuples to the existing dict
.
>>> student_dict = {"00-01-30": "Ali", "00-02-11": "Simon",
... "00-05-67": "Francesca", "00-09-88": "Cho"
... }
...
>>> student_dict.update({"00-03-55": "Jose", "00-07-21": "Debora"})
>>> print(student_dict)
{'00-01-30': 'Ali', '00-02-11': 'Simon', '00-05-67': 'Francesca',
'00-09-88': 'Cho', '00-03-55': 'Jose', '00-07-21': 'Debora'}
>>> student_dict.update([("00-04-01", "Christina"), ("00-06-34", "Gerwazy")])
>>> print(student_dict)
{'00-01-30': 'Ali', '00-02-11': 'Simon', '00-05-67': 'Francesca',
'00-09-88': 'Cho', '00-03-55': 'Jose', '00-07-21': 'Debora',
'00-04-01': 'Christina', '00-06-34': 'Gerwazy'}
setdefault()
The .setdefault()
method is similar to the .get()
method. The main difference is that .setdefault()
also adds the new key with a default value to the dict
if the key does not exist.
>>> student_dict = {"00-01-30": "Ali", "00-02-11": "Simon",
... "00-05-67": "Francesca", "00-09-88": "Cho"
... }
...
>>> existing_student = student_dict.setdefault("00-09-88", "John Doe")
>>> print(existing_student)
Cho
>>> print(student_dict)
{'00-01-30': 'Ali', '00-02-11': 'Simon', '00-05-67': 'Francesca', '00-09-88': 'Cho'}
>>> new_unknown_student = student_dict.setdefault("11-22-33", "John Doe")
>>> print(new_unknown_student)
John Doe
>>> print(student_dict)
{'00-01-30': 'Ali', '00-02-11': 'Simon', '00-05-67': 'Francesca', '00-09-88': 'Cho',
'11-22-33': 'John Doe'}