Container Data Structures
Dictionaries and Sets in Detail
Sets contain unique values, as the definition suggests. Dictionaries are special form of sets that contain key:value
pairs based on unique set of key
entries. The same value
can be reassigned to different keys. Any reassignment to or update()
of a specific key
will overwrite the existing value
of that key. The set of keys in a dictionary can be retrieved by the keys()
method.
The get()
function has the similar result of accessing the dictionary items using the access operator []
:
balance_dict = {
"Alice":1345.345,
"Claire":15642.432,
"Spiderman":1234366.4352}
print("Alice has %10.2f units of balance\n" % (balance_dict.get("Alice")))
balance_dict["Alice"] = 3500.365
for key in balance_dict.keys():
print("Balance of %10s is %10.2f" % (key, balance_dict[key]))
if key == "Claire":
balance_dict.update({"Claire":25000.453})
print("Balance of %10s is %10.2f" % (key, balance_dict.get(key)))
Output:
Alice has 1345.35 units of balance
Balance of Alice is 3500.36
Balance of Alice is 3500.36
Balance of Claire is 15642.43
Balance of Claire is 25000.45
Balance of Spiderman is 1234366.44
Balance of Spiderman is 1234366.44
A view
of dict_items
can be generated by the items()
method, where the view will be automatically updated if the dictionary is modified:
balance_dict = {
"Alice":1345.345,
"Claire":15642.432,
"Spiderman":1234366.4352}
print("Alice has %10.2f units of balance\n" % (balance_dict.get("Alice")))
items_view = balance_dict.items()
print(items_view)
balance_dict["Alice"] = 3500.365
print(items_view)
Output:
Alice has 1345.35 units of balance
dict_items([('Alice', 1345.345), ('Claire', 15642.432), ('Spiderman', 1234366.4352)])
dict_items([('Alice', 3500.365), ('Claire', 15642.432), ('Spiderman', 1234366.4352)])
The in
keyword acts as an iteration operator when used in a for
loop. Similar to the strings and lists, the in
keyword can be used to find out whether a given argument is present in a set or in the key set of a dictionary:
balance_dict = {
"Alice":1345.345,
"Claire":15642.432,
"Spiderman":1234366.4352}
def display_balance(account_owner):
if account_owner in balance_dict:
print("%15s has %10.2f units of balance" % (account_owner, balance_dict.get(account_owner)))
else:
print("%15s does not have an account" % account_owner)
display_balance("Alice")
display_balance("Batman")
Output:
Alice has 1345.35 units of balance
Batman does not have an account