Container Data Structures

Dictionary Operations

When an existing dictionary variable is assigned to another variable, both variables refer to the same dictionary instance, i.e. modifications on either one will be reflected to the other. An independent copy of the dictionary can be produced by using the copy() or dict() methods:

students = {
    20009001: "Alice",
    20009002: "Claire",
    20009003: "Joker",
    20009004: "Spiderman"}

students_temp = students
students[20009005] = "Batman"

print(students_temp)

students_temp = students.copy()
students[20009006] = "Ghida"

print(students)
print(students_temp)

students_temp = dict(students)
print(students_temp)

Output:

{20009001: 'Alice', 20009002: 'Claire', 20009003: 'Joker', 20009004: 'Spiderman', 20009005: 'Batman'}
{20009001: 'Alice', 20009002: 'Claire', 20009003: 'Joker', 20009004: 'Spiderman', 20009005: 'Batman', 20009006: 'Ghida'}
{20009001: 'Alice', 20009002: 'Claire', 20009003: 'Joker', 20009004: 'Spiderman', 20009005: 'Batman'}
{20009001: 'Alice', 20009002: 'Claire', 20009003: 'Joker', 20009004: 'Spiderman', 20009005: 'Batman', 20009006: 'Ghida'}

Constructing a new dictionary using a list of tuples:

st_list = [ ("Alice",20), ("Michael",19)]
student_tt = dict(st_list)

print(student_tt)
print(student_tt["Michael"])

The values of dictionaries can be any type including other dictionaries.

If you need composite keys in your dictionary consisting of multiple items, then you need tuples as the key. On the other hand, lists cannot be used as keys as tuples are hashable and lists are not:

balance_dict = {}

balance_dict["Alice", "Morgan"] = 1345.345
balance_dict["Claire", "McMillan"] = 15642.432

print(balance_dict)

will output {('Alice', 'Morgan'): 1345.345, ('Claire', 'McMillan'): 15642.432}, with tuples as the composite keys.

Using a list as the key in the same example

balance_dict = {}
balance_dict[["Claire", "McMillan"]] = 15642.432

will generate the following error

TypeError: unhashable type: 'list'