Python Dictionary
A dictionary in Python is a data structure to store data in Key: value format. There are several similarities between python lists and dictionaries, however, they differ in how their elements are accessed. List elements are ordered and are accessed by numerical index, dictionary’s items on the other hand are unordered and are accessed by key.
Each individual data point in a dictionary is called an item. It’s separated by a comma, An example dictionary in python would look like below.
dictionary {
'key': 'value',
'key2' :'value2'
}
Key Properties of Python Dictionary
A python dictionary has the following key properties
Ordered
Dictionaries are ordered. What it means is that order of the items within a dictionary is fixed. And that order will not change. Dictionaries are ordered from python version 3.7 onwards. In python version 3.6 and prior, dictionaries are unordered.
Changeable
Dictionaries are changeable. What it means is that we can add, remove items from the dictionaries after they have been created.
Duplicates are not allowed
Dictionaries do not allow duplicate keys. Any duplicate key will be overwritten by the later key.
Melbourne = {
'Area': '9,993 sq.km',
'Population' :'4,963,349',
2021 :'impacted by covid',
2021 :'Year of coffee'
}
This will print 2021 as ‘Year of coffee”, overwriting the previous value of the key.
Creating Dictionary in Python
Empty dictionary using {}
We can create an empty dictionary in python using the {} operator.
# Creating an empty dictionary
Melbourne = {}
Dictionary with items
We can also create a dictionary by specifying any items list separated by commas.
#Creating dictionary with items
Melbourne = {
'Area': '9,993 sq.km',
'Population' :'4,963,349',
2021 :'impacted by covid'
}
Notice the if the key is text, we have to include it in quotes. If it’s a numeric value, it does not need to be in quotes.
Dictionary with dict()
We can also use dict() function in python to create a dictionary.
Melbourne = dict({
'Area': '9,993 sq.km',
'Population' :'4,963,349',
2021 :'impacted by covid'
})
Accessing Dictionary Items
Python dictionaries provide a few functions to access both keys and values of dictionary items.
Accessing All Key:Value items using .items()
dictionary.items() function gives a list of all key-value pairs in the dictionary.
Melbourne = dict({
'Area': '9,993 sq.km',
'Population' :'4,963,349',
2021 :'impacted by covid'
})
result = Melbourne.items()
print(result)
dict_items([('Area', '9,993 sq.km'), ('Population', '4,963,349'), (2021, 'impacted by covid')])
Accessing Keys Only using .keys()
.keys() function is used to get only the keys of all items. If we replace the .items() function with .keys() function in the code above. It will only return keys this time.
result = Melbourne.keys()
print(result)
dict_keys(['Area', 'Population', 2021])
Accessing Item Values
There are two main functions for accessing item values
Using []
We can access specific dictionary item by providing it’s key either explicitly or in a loop. In the example below, I am providing an explicit key.
print(Melbourne['Area'])
9,993 sq.km
Using .get()
Another way of accessing an item value is by using dictionary.get() function
print(Melbourne.get('Area'))
9,993 sq.km
Removing items
Python provides two main function for removing either the key or the key:value pair from the dictionary.
Removing item using .pop()
dictionary.pop() function removes an item from the dictionary and returns its associated value.
#poping key Area
print( Melbourne.pop('Area') )
#resulting dictionary after pop
print(Melbourne)
9,993 sq.km
{'Population': '4,963,349', 2021: 'impacted by covid'}
Removing last item using .popitem()
dictionary.popitem() removes the last key-value paid added and returns it as a tuple.
#poping key Area
print(Melbourne.popitem())
#resulting dictionary after pop
print(Melbourne)
(2021, 'impacted by covid')
{'Area': '9,993 sq.km', 'Population': '4,963,349'}