Dictionary
A dictionary is an unordered built-in data structure in Python that allows you to store and work on collections of key-value pairs. In a dictionary, each key is unique (no duplicates) and is associated with a value. Other programming languages use different terms for dictionaries such as hash, map, and table. A dictionary can be thought of as a table with two columns (one for the key, the other for the value) and multiple rows (representing multiple pairs). Data that exhibits this structure is perfect for a dictionary.
Example:
Name: Joe
Gender: Male
Department: Engineering
A dictionary consists of key, value pairs that are enclosed in curly brackets (or curly braces). The key is separated from its associated value using a colon (:). Each key, value pair is separated from the next pair using a comma. Unlike lists in Python, which are ordered and maintain insertion order, dictionaries are unordered meaning that the order of the data is not maintained inside the dictionary. The order that you input the pairs when you create the dictionary is not what will be displayed. However, this is not an issue since when data is selected (or referred to), the selection is based on the key.
employee = { ‘Name’: ‘Joe’,
‘Gender’: ‘Male’,
‘Occupation’: ‘Engineer’ }
Each key, value pair is written on a separate line in order to make the dictionary easy to read. A dictionary can be thought of as a lookup table whereby the key on the left is used to look up the value to its right.
Use of Square Brackets to Select/Access Data
Just like lists that make use of square brackets, dictionaries also use square brackets to access data. The square bracket notation is also used to add key, and value pairs to a dictionary. However, unlike lists that use index value inside the square brackets to point to an object, dictionaries use the key inside the square brackets to access the value associated with it.
Example 1:
# Dictionary makes use of brackets to access or select data from within a dict
employee = {'name': 'Joe',
'gender': 'Male',
'department': 'engineering'}
print(employee['name']) # Prints the employee's name
Joe
Example 2:
# A Dictionary makes use of brackets to add a new key, and value pair to dict
employee = {'name': 'Joe',
'gender': 'Male',
'department': 'engineering'}
employee['age'] = 99 # adds a new key/value pair to the dictionary
print(employee) # Prints employee dict after adding new key/value pair
{'name': 'Joe', 'gender': 'Male', 'department': 'engineering', 'age': 99}
Python’s for loop can be used to iterate over a dictionary
The items() method is used to return a list of key, value pairs in the form of tuples. On each iteration, the key and value are assigned to the loop variables (for example, k & v), which are then used to access the data value.
employee = {'name': 'Joe',
'gender': 'Male',
'department': 'engineering'}
for k, v in employee.items(): # items() method returns key, value pairs in the form of tuples
print("The employee's", k, 'is', v)
The employee's name is Joe
The employee's gender is Male
The employee's department is engineering
>>>
The sorted in-built function can be used to sort the key, value pairs based on the key.
for k, v in sorted(employee.items()): # sorted() in-built function sorts dict based on keys
print("The employee's", k, 'is', v)
The employee's department is engineering
The employee's gender is Male
The employee's name is Joe
>>>
The built-in function dir can be used to display the attributes and methods associated with dictionaries.
dir(dict) # Use dir (built-in function) to view dictionary attributes and methods
The built-in function, help, can be used to display more details on the different methods and attributes associated with dictionaries.
help(dict.pop) # Use help to view details on dict attributes and methods
Initializing Dictionary Keys – Avoid KeyErrors at Runtime
Some situations may require that the keys be initialized during runtime. Caution has to be taken to avoid raising a KeyError (this is a runtime error that will cause the program to crash),which may occur when accessing a value that is associated with a key that does not exist. Here, if a key is nonexistent, then the associated value cannot be found.
Example 1:
# Initializing dictionary keys to avoid KeyErrors at Runtime
fruit_count= {'apples': 4}
fruit_count ['oranges'] += 1 # KeyError exception is raised since the key ‘oranges’ does not exist
#fruit_count['oranges'] = 0 # Initialize oranges to value of zero
#fruit_count ['oranges'] += 1 # Here no KeyError exception. The value of apples is incremented by one
print(fruit_count)
{'apples': 4, {'oranges': 1}
}
Just like with a list, we can use the not in operator to first determine if a key already exists in a given dictionary before we attempt to access it. Use of the not in operator returns True or False based on whether the key is found inside the dictionary. We will demo this approach by using the not in operator to check whether a fruit exists inside our fruit_count. If the fruit does not exist in the dictionary, we initialize the fruit with a value of one, otherwise, we increment the value by one.
Example:
fruit_count = { 'apples': 2, 'bananas': 5 }
if 'pears' not in fruit_count: # We check to see if ‘oranges’ key is in dict. If not, we initialize by one.
fruit_count['oranges'] = 1
else:
fruit_count['oranges'] += 1 # If ‘oranges’ key already exists in the dictionary, we increment the value by 1.
print(fruit_count)
{ 'apples': 2, 'bananas': 5, 'pears': 1 }
setdefault method
The setdefault dictionary method allows us to initialize key values in an easier and more convenient manner. The setdefault method will only initialize a value of a non-existing key and does not affect the value of a key that already exists. The setdefault method is often leveraged to avoid raising the KeyError exception during runtime.
Example:
fruit_count.setdefault(‘oranges’, 0) # set the default to one if ‘oranges’ key does not exist
fruit_count[‘oranges’] += 1 # increments ‘oranges’ associated value by one
Nested Dictionaries
A nested dictionary is one that contains dictionaries inside of it. For instance, the value of a key inside a dictionary will consist of a dictionary.
Example:
employees = {'employee1': {'name': 'Joe','gender': 'Male','department': 'Engineering'},
'employee2': {'name': 'Inno', 'gender': 'Male', 'department': 'IT'}}
>>> print(employees)
{'employee1': {'name': 'Joe', 'gender': 'Male', 'department': 'Engineering'}, 'employee2': {'name': 'Inno', 'gender': 'Male', 'department': 'IT'}}
>>> print(employees['employee2']) # Access value associated with key 'employee2'
{'name': 'Inno', 'gender': 'Male', 'department': 'IT'}
print(employees['employee2']['name']) # Access name for employee2
>>> print(employees['employee2']['name'])
Inno
Sets in Python
A set is an unordered built-in data structure that does not allow/contain duplicates (cannot have two items/objects of the same value). Sets have some mathematical properties such as union and intersection that can come in handy in certain situations. A set is made up of objects that are separated by commas and are contained inside curly braces.
Example:
set1 = { 75, 80, 85, 90 }
set2 = { 75, 80, 95, 98 }
Set Methods
Some of the set methods include union, intersection, and symmetric_difference
union() method
Joins two sets returns a new set that contains all items from both sets. Removes duplicates.
Example:
set1 = { 75, 80, 85, 90 }
set2 = { 75, 80, 95, 98 }
>>> set3 = set1.union(set2)
>>> print(set3)
{98, 75, 80, 85, 90, 95}
>>>
intersection() method
Returns a new set that contains only the items that are common in the two sets.
Example:
set1 = { 75, 80, 85, 90 }
set2 = { 75, 80, 95, 98 }
>>> set3 = set1.intersection(set2)
>>> print(set3)
{80, 75}
symmetric_difference() method
Returns a new set, that contains only the elements that are not common in both sets.
Example:
>>>
>>> set1 = { 75, 80, 85, 90 }
>>> set2 = { 75, 80, 95, 98 }
>>> set3 = set1.symmetric_difference(set2)
>>> print(set3)
{98, 85, 90, 95}
>>>
Conclusion
In this article, we introduced the concept of Dictionaries in the Python programming language. We defined what a dictionary is and showed examples using the proper syntax. The article also explained the aspect of accessing data within a dictionary by leveraging the square brackets syntax. Examples were used to demonstrate how this can be done. Additionally, a few methods associated with Dictionaries were illustrated.