Python Data Structures — Dictionary
Prerequisites : Basic knowledge of any programming language
we will explore Data Structure Dictionary and its common operations here.
Jupyter notebook on Dictionary
Dictionary is unordered set of key value pairs where keys should be unique within a dictionary.
Dictionaries are indexed by keys, they are mutable and dynamic- they can grow and shrink. The key and values can have any data type like strings or numbers.
Now we will go step by step into defining a dictionary, Adding elements in a dictionary, updating elements in a dictionary, removing elements from a dictionary and retrieving the elements in a dictionary, iterating through the dictionary
all outputs are in bold and italics
Defining a Dictionary
It is defined using a pair of empty braces{}.
Contact_info = {}key value pairs are separated by a comma and a colon(:) separates a key from its value.
In the below example, Name is the key and ‘Jane Dow’ is value associated with it
Contact_info = {'Name':'Jane Dow',
'Address':'1800 SW'
}
Contact_info{'Address': '1800 SW', 'Name': 'Jane Dow'}Adding elements to a dictionary
To add an element, we need to specify the key and value. Here the key is “Mobile” and value is a number 1234567
Contact_info["Mobile"] = 1234567
Contact_info{'Address': '1800 SW', 'Mobile': 1234567, 'Name': 'Jane Dow'}Another way to add elements to a dictionary can be done using Update() method. update() -updates the dictionary with the specified key value pair
Contact_info.update({"email":"[email protected]"})
Contact_info{'Address': '1800 SW',
'Mobile': 9999999,
'Name': 'Jane Dow',
'email': '[email protected]'}we can also pass a dictionary as an argument to update() method. Like we have dictionary data_1 and we add its contents to Contact_info dictioanry
data_1={'City':'New York', 'Zip':51234}
Contact_info.update(data_1)
Contact_info{'Address': '1800 SW',
'City': 'New York',
'Mobile': 9999999,
'Name': 'Jane Dow',
'Zip': 51234,
'email': '[email protected]'}Updating value of an existing key in the dictionary
specify the key and provide the new value
Contact_info["Mobile"] = 9999999
Contact_info{'Address': '1800 SW', 'Mobile': 9999999, 'Name': 'Jane Dow'}Retrieving contents of a dictionary
we can retrieve values of a dictionary by specifying its key as shown below
print(Contact_info['Name'])
print(Contact_info['email'])Jane Dow
abc@domain.comwe can also use get() method to access the value of a key by passing key as an argument.
Contact_info.get('Address')'1800 SW'For accessing all the keys in a dictionary
print(Contact_info.keys())dict_keys(['Name', 'Address', 'Mobile', 'email', 'City', 'Zip'])For accessing all the values in a dictionary
print(Contact_info.values())dict_values(['Jane Dow', '1800 SW', 9999999, '[email protected]', 'New York', 51234])Deleting items in a dictionary
To delete an Item in the dictionary we can use del
del Contact_info[“email”]
Contact_info{'Address': '1800 SW',
'City': 'New York',
'Mobile': 9999999,
'Name': 'Jane Dow',
'Zip': 51234}If you want to clear the contents of the entire dictionary then use clear() as shown below
State_capital ={'Arkansas':'Little Rock', 'Wisconsin':'Madison', 'California':'Sacramento', 'Iowa':'Des Moines'}
State_capital{'Arkansas': 'Little Rock',
'California': 'Sacramento',
'Iowa': 'Des Moines',
'Wisconsin': 'Madison'}State_capital.clear()
State_capital{}we can also use pop() to remove a specific item by passing the key of the item as an argument.
In the below example, we use pop() to remove the item for “Iowa” from the dictionary
State_capital ={'Arkansas':'Little Rock', 'Wisconsin':'Madison', 'California':'Sacramento', 'Iowa':'Des Moines'}
State_capital.pop("Iowa")
State_capital{'Arkansas': 'Little Rock',
'Wisconsin': 'Madison',
'California': 'Sacramento'
}we can also use popitem() method to remove the last key value pair. It returns the key value removed from dictionary
State_capital.popitem()('California', 'Sacramento')State_capital{'Arkansas': 'Little Rock', 'Wisconsin': 'Madison'}Iterating through a Dictionary
There are different methods to iterate over a dictionary. The simplest is to use a for loop
for i in Contact_info:
print(Contact_info[i])Jane Dow
1800 SW
9999999
New York
51234Next we will use dictionary comprehension, which is like a shortcut for the for loop in a single statement
state_capital={
'New York': 'Albany',
'New Jersey': 'Trenton',
'Arkansas':'Little Rock',
'Wisconsin':'Madison',
'Illinois':'Springfield',
'Iowa':'Des Moines',
'California':'Sacramanto'
}dict_capital = {key:value for (key,value) in state_capital.items()}
print(dict_capital){'New York': 'Albany', 'New Jersey': 'Trenton', 'Arkansas': 'Little Rock', 'Wisconsin': 'Madison', 'Illinois': 'Springfield', 'Iowa': 'Des Moines', 'California': 'Sacramento'}Conditional Search
Again we can use a simple for loop and an if statement inside it for search for a specific condition like shown below where we are searching the capitial of “Iowa”
search_state ='Iowa'
for state in state_capital:
if search_state == state:
print(state_capital[state])Des MoinesNow using a conditional search using dictionary comprehension. Here we are want to show all the counties in a state. we search for “Arkansas” and then show the values
counties_in_state={
'New York': 'Albany',
'New Jersey': 'Trenton',
'Arkansas':'Little Rock, Bentonville, Rogers, Fayetteville',
'Wisconsin':'Madison, Milwaukee',
'Illinois':'Springfield, chicago',
'Iowa':'Des Moines',
'California':'Sacromanto, San Francisco, Los Angeles'
}
counties = {value for (key,value) in counties_in_state.items() if key == 'Arkansas'}
print(counties){'Little Rock, Bentonville, Rogers, Fayetteville'}Dictionary Operations quick reference
clear() : Removes all the elements from the dictionary
get() : Returns the value of the specified key
items() : Returns a list containing tuple for each key value pair in the dictionary
values() : Returns a list of all the values in the dictionary
copy() : Returns a shallow copy of the dictionary
update() : Updates the dictionary with the specified key-value pairs
pop() : Removes the element with the specified key
popitem() : Removes the last key-value pair
setdefault() : Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
Let me know how I can make my posts better by leaving me a comment
