Dictionary#

Dictionaries are used to store and manipulate datasets for efficient search and retrieval of values based on their associated keys.

  • A dictionary is a collection of key-and-value pairs

  • Dictionary is unordered, mutable, and indexed collection of elements, where each element is a key-value pair separated by a colon and enclosed in curly braces.

Note

General syntax

my_dict = {key1: value1,
            key2: value2,
            key3: value3,
            keyN: valueN}
  • my_dict: Dictionary variable name

  • key1, key2, key3, …, keyN: The keys are used to find each value in the dictionary, and can be strings, integers etc.

  • value1, value2, value3, …, valueN: In each key, you can store values of any data type (lists, springs, other dictionary).

Examples#

# Create an empty dictionary
d = dict()
# or
d = {}
# Create a dictionary with different key-value pairs
dict_test = {
    "a": "test",
    "b": 1000,
    "c": [1,2,3],
    1: 'name'
}
# print, modify, print again
print(dict_test['b'])
1000
# modify the value of key 'b'
dict_test['b'] = 2000
print(dict_test['b'])
2000
# see the keys
print(dict_test.keys())
dict_keys(['a', 'b', 'c', 1])
# see the values
print(dict_test.values())
dict_values(['test', 2000, [1, 2, 3], 'name'])

Another example:

# Create a dictionary of ABE's details
abe_program = {
    "program": "biosystems engineering",
    "n_students": 1000,
    "aplication": "land and water management"
}
# Access the values of a dictionary
print(abe_program["program"])    # biosystems engineering
print(abe_program["n_students"])     # 1000
print(abe_program["aplication"])   # land and water management
biosystems engineering
1000
land and water management
# Update the values of a dictionary
abe_program["n_students"] = 1500
abe_program["aplication"] = "biomedical analysis"
print(abe_program["n_students"])   # biomedical analysis
print(abe_program["aplication"])   # biomedical analysis
1500
biomedical analysis
# Add a new key-value pair to a dictionary
abe_program["university"] = "Mississippi State University"
print(abe_program["university"])
Mississippi State University
# Delete a key-value pair from a dictionary
del abe_program["aplication"]
# Iterate over the keys of a dictionary
for key in abe_program.keys():
    print(key)
program
n_students
university
# Iterate over the values of a dictionary
for value in abe_program.values():
    print(value)
biosystems engineering
1500
Mississippi State University
# Iterate over the key-value pairs of a dictionary
for key, value in abe_program.items():
    print(key, value)
program biosystems engineering
n_students 1500
university Mississippi State University