Python Dictionaries

Dictionary

A dict is a data type that stores a sequence of key:value pairs (a key is associated with a value). Keys have to be immutable and cannot be duplicated. Notice that dict and set use the same syntax {} . A dict will have key:value pairs, whereas a set, will only have values. Dictionaries are also known as associative arrays or hash tables.

Example

dict_1 = {“key_1”: “value_1”, “key_2”: “value_2”} # Create a dictionary with key-value pairs
set_1 = {“value_1”, “value_2”} # Create a set with two unique values
print(type(dict_1), “=”, dict_1) # Print the type of dict_1 and its contents
print(type(set_1), “=”, set_1) # Print the type of set_1 and its contents

dict_1 = {"key_1":"value_1","key_2":"value_2"}
set_1 = {"value_1","value_2"}

print(type(dict_1), "=", dict_1)
print(type(set_1), "=", set_1)

Result

<class 'dict'> = {'key_1': 'value_1', 'key_2': 'value_2'}
<class 'set'> = {'value_2', 'value_1'}

Structuring Data

Dictionaries are very powerful – Let’s say that following is a list of users in a company:

  • Jim drives a Toyota Tacoma 2010, and he is 44 years old
  • Sara drives a Ford F-150 2021, and she is 31 years old

We can have that organized into a dict

{
"Users": {
"Jim": {
"car": "Toyota Tacoma 2010",
"age": 44
},
"Sara": {
"car": "Ford F-150 2021",
"age": 31
}
}
}

Or, we can structure that in a list of dictionaries

[
{
"name": "Jim",
"car": "Toyota Tacoma 2010",
"age": 44
},
{
"name": "Sara",
"car": "Ford F-150 2021",
"age": 31
}
]

Or, more structured (The more structured, the easier to search or analyze)

[
{
"name": "Jim",
"car": {
"model": "Tacoma",
"make": "Toyota",
"year": 2010
},
"age": 44
},
{
"name": "Sara",
"car": {
"model": "F-150",
"make": "Ford",
"year": 2021
},
"age": 31
}
]

Accessing Values

You can access a value by its key. If you have a dict named temp_dict that contains {"key_1":"value_1","key_2":"value_2"}, then you can access the value_1 by using key_1 as temp_dict["key_1"] and so on.

Example

temp_dict = {“key_1”: “value_1”, “key_2”: “value_2”} # Create a dictionary with two key-value pairs
print(temp_dict[“key_1”]) # Access the value associated with the key “key_1” and print it

temp_dict = {"key_1":"value_1","key_2":"value_2"}

print(temp_dict["key_1"])

Result

value_1

Or you can use the .get method

Example

temp_dict = {“key_1”: “value_1”, “key_2”: “value_2”} # Create a dictionary with two key-value pairs
print(temp_dict[“key_1”]) # Access the value associated with the key “key_1” using the method .get and print it

temp_dict= {"key_1":"value_1","key_2":"value_2"}
print(temp_dict.get("key_1"))

Result

value_1

Get All Keys

To get the keys of a dict, you can use the .keys method

Example

temp_dict = {“key_1”: “value_1”, “key_2”: “value_2”} # Create a dictionary with two key-value pairs
print(temp_dict[“key_1”]) # Print all temp_dict keys

temp_dict = {"key_1":"value_1","key_2":"value_2"}

print(temp_dict.keys())

Result

dict_keys(['key_1', 'key_2'])

Get All Values

To get the values of a dict, you can use the .values method

Example

temp_dict = {“key_1”: “value_1”, “key_2”: “value_2”} # Create a dictionary with two key-value pairs
print(temp_dict[“key_1”]) # Print all temp_dict values

temp_dict = {"key_1":"value_1","key_2":"value_2"}
print(temp_dict.values())

Result

dict_values(['value_1', 'value_2'])

Add or Update key:value Pair

You can use the update method to add a new pair or update a current pair. Remember that a dict cannot have duplicate keys. So, if you use an existing key, the value will be updated. Otherwise, a new pair will be added to the dict

Example

temp_dict = {“key_1”: “value_1”, “key_2”: “value_2”} # Create a dictionary with two key-value pairs
temp_dict.update({“key_1”: “new_value”}) # Update the value of “key_1” to “new_value”
print(temp_dict) # Print the updated dictionary
temp_dict.update({“key_3”: “value_3”}) # Add a new key-value pair “key_3”: “value_3” to the dictionary
print(temp_dict) # Print the updated dictionary

temp_dict = {"key_1":"value_1","key_2":"value_2"}

temp_dict.update({"key_1":"new_value"})print(temp_dict)

temp_dict.update({"key_3":"value_3"})print(temp_dict)

Result

{'key_1': 'new_value', 'key_2': 'value_2'}
{'key_1': 'new_value', 'key_2': 'value_2', 'key_3': 'value_3'}

Modify a value by its Key

You can use the assignment statement = with the value corresponding key

Example

temp_dict = {“key_1”: “value_1”, “key_2”: “value_2”} # Create a dictionary with two key-value pairs
temp_dict[“key_1”] = “new_value” # Update the value of “key_1” to “new_value”
print(temp_dict[“key_1”]) # Access and print the updated value of “key_1”

temp_dict = {"key_1":"value_1","key_2":"value_2"}

temp_dict["key_1"] = "new_value"
print(temp_dict["key_1"])

Result

new_value

Length

You can use the len function, which will return the number of keys

Example

temp_dict = {“key_1”: “value_1”, “key_2”: “value_2”} # Create a dictionary with two key-value pairs
print(len(temp_dict)) # Print the number of key-value pairs in the dictionary

temp_dict = {"key_1":"value_1","key_2":"value_2"}

print(len(temp_dict))

Result

2

Delete a key:value Pair

To delete a key:value pair, use the del function with the key

Example

temp_dict = {“key_1”: “value_1”, “key_2”: “value_2”} # Create a dictionary with two key-value pairs
del(temp_dict[“key_1”]) # Delete the key-value pair with key “key_1” from the dictionary
print(temp_dict) # Print the updated dictionary

temp_dict = {"key_1":"value_1","key_2":"value_2"}

del(temp_dict["key_1"])print(temp_dict)

Result

{'key_2': 'value_2'}
new_value

Pass By Reference

A dict is an immutable objects are passed by reference to function

def change_value(param_in): # Define a function that takes one parameter called param_in
    param_in.update({2: “test”}) # Update the dictionary by adding a new key-value pair 2: “test”
var = {1: “test”} # Create a dictionary with one key-value pair 1: “test”
print(“Value before passing: “, var) # Print the dictionary before calling the function
change_value(var) # Call the function; the dictionary is modified inside the function
print(“Value after passing: “, var) # Print the dictionary after the function call

Example

def change_value(param_in):
    param_in.update({2:"test"})

var = {1:"test"}

print("Value before passing: ", var)
change_value(var)
print("Value after passing: ", var)

Result

Value before passing:  [0, 1, 2, 3, 4, 5]
Value after passing:  [0, 1, 2, 3, 4, 5, 99]