Container Data Structures
Dictionary Methods
Items in a dictionary can be removed by using the pop()
method or the del
keyword:
balance_dict = {
"Alice":1345.345,
"Claire":15642.432,
"Joker":14542.782,
"Spiderman":1234366.4352}
balance_dict.pop("Spiderman")
del balance_dict["Claire"]
print(balance_dict)
balance_dict.pop("Batman")
Output:
{'Alice': 1345.345, 'Joker': 14542.782}
Traceback (most recent call last):
File ..., line 13, in <module>
balance_dict.pop("Batman")
KeyError: 'Batman'
The contents of a directory or set can be removed entirely by using the clear()
method and the del
keyword can be used to delete the directory or set variable making it inaccessible:
balance_dict = {
"Alice":1345.345,
"Claire":15642.432,
"Joker":14542.782,
"Spiderman":1234366.4352}
print(balance_dict)
balance_dict.clear()
print(balance_dict)
del balance_dict
print(balance_dict)
Output:
{'Alice': 1345.345, 'Claire': 15642.432, 'Joker': 14542.782, 'Spiderman': 1234366.4352}
{}
Traceback (most recent call last):
..., line 11, in <module>
print(balance_dict)
NameError: name 'balance_dict' is not defined
Items can be removed from a set by using the remove()
function, however pop()
method may remove a random element from the set each time the code is executed, be careful when using:
students = {
"Alice",
"Claire",
"Joker",
"Spiderman"}
students.remove("Joker")
print(students)
Output:
{'Spiderman', 'Alice', 'Claire'}, or
{'Alice', 'Claire', 'Spiderman'}, or other ordering
Using the in
keyword, the items in the dictionary can be accessed either directly or by using the keys()
method. Similarly the values()
method returns the list of values in the dictionary entries. As we have covered earlier, the items()
method returns the key-value pairs as iterable tuples which can be assigned to two variables corresponding to key and value respectively:
balance_dict = {
"Alice":1345.345,
"Claire":15642.432,
"Joker":14542.782,
"Spiderman":1234366.4352}
for account_name in balance_dict:
print(account_name)
print()
for account_name in balance_dict.keys():
print(account_name)
print()
for balance in balance_dict.values():
print(balance)
print()
for account_name, balance in balance_dict.items():
print(account_name + " " + str(balance))
print()
Output:
Alice
Claire
Joker
Spiderman
Alice
Claire
Joker
Spiderman
1345.345
15642.432
14542.782
1234366.4352
Alice 1345.345
Claire 15642.432
Joker 14542.782
Spiderman 1234366.4352