Dictionaries in Python

Index

Definition

A dictionary is a collection of an unordered set of key:value pairs, with the requirement that the keys are unique within a dictionary.

Dictionaries are constructed using curly braces { }, wherein you include a list of key:value pairs separated by commas.

Also, there is a colon (:) separating each of these key and value pairs, where the words to the left of the colon operator are the keys and the words to the right of the colon operator are the values.

Unlike lists, which are indexed by a range of numbers, dictionaries are indexed by keys. Here a key along with its associated value is called a key:value pair.

Dictionary keys are case sensitive.

The syntax for creating a dictionary is,

dictionary_name = {key_1:value_1, key_2:value_2, key_3:value_3, ………,key_n:value_n}

Example

>>> fish = {"g": "goldfish", "s":"shark", "n": "needlefish", "b":"barramundi", 
"m":"mackerel"}

>>> fish
 {'g': 'goldfish', 's': 'shark', 'n': 'needlefish', 'b': 'barramundi', 'm': 'mackerel'}

Operations on Dictionaries

Accessing and Modifying key: value Pairs in Dictionaries

Each individual key:value pair in a dictionary can be accessed through keys by specifying it inside square brackets. The key provided within the square brackets indicates the key:value pair being accessed.

The syntax for accessing the value for a key in the dictionary is,

dictionary_name[key]

The syntax for modifying the value of an existing key or for adding a new key:value pair to a dictionary is,

dictionary_name[key] = value

If the key is already present in the dictionary, then the key gets updated with the new value. If the key is not present then the new key:value pair gets added to the dictionary.

For example,

>>> renaissance = {"giotto":1305, "donatello":1440, "michelangelo":1511, 
"botticelli":1480, "clouet":1520}
>>> renaissance["giotto"] = 1310
>>> renaissance
{'giotto': 1310, 'donatello': 1440, 'michelangelo': 1511, 'botticelli': 1480, 'clouet': 1520}
>>> renaissance["michelangelo"]
1511
>>> renaissance["leonardo"] = 1503
>>> renaissance
{'giotto': 1310, 'donatello': 1440, 'michelangelo': 1511, 'botticelli': 1480, 'clouet': 1520, 
'leonardo': 1503}
>>> renaissance["piero"]
 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 KeyError: 'piero'

Since dictionaries are mutable, you can add a new key:value pair or change the values for existing keys using the assignment operator.

You can add a new key:value pair by specifying the name of the dictionary followed by a bracket within where you specify the name of the key and assign a value to it.

If you try to access a non-existing key then it results in KeyError.

Built-in Functions on Dictionaries

There are many built-in functions for which a dictionary can be passed as an argument

Built-in FunctionsDescription
len()The len() function returns the number of items (key:value pairs) in a dictionary.
all()The all() function returns Boolean True value if all the keys in the dictionary are True else returns False.
any()The any() function returns Boolean True value if any of the key in the dictionary is True else returns False.
sorted()The sorted() function by default returns a list of items, which are sorted based on dictionary keys.

Example,

>>> presidents = {"washington":1732, "jefferson":1751, "lincoln":1809, 
"roosevelt":1858, "eisenhower":1890}
>>> len(presidents)
5
>>> all_dict_func = {0:True, 2:False}
>>> all(all_dict_func)
False
>>> all_dict_func = {1:True, 2:False}
>>> all(all_dict_func)
True
>>> any_dict_func = {1:True, 2:False}
>>> any(any_dict_func)
True
>>> sorted(presidents)
['eisenhower', 'jefferson', 'lincoln', 'roosevelt', 'washington']
>>> sorted(presidents, reverse = True)
['washington', 'roosevelt', 'lincoln', 'jefferson', 'eisenhower']
>>> sorted(presidents.values())
[1732, 1751, 1809, 1858, 1890]
>>> sorted(presidents.items())
 [('eisenhower', 1890), ('jefferson', 1751), ('lincoln', 1809), ('roosevelt', 1858), 
('washington', 1732)]

Dictionary Methods

Various Dictionary Methods

Dictionary MethodsSyntaxDescription
clear()dictionary_name.clear()The clear() method removes all the key:value pairs from the dictionary.
fromkeys()dictionary_name.fromkeys(seq[, value])The fromkeys() method creates a new dictionary from the given sequence of elements with a value provided by the user.
get()dictionary_name.get(key[, default])The get() method returns the value associated with the specified key in the dictionary. If the key is not present then it returns the default value. If default is not given, it defaults to None, so that this method never raises a KeyError.
items()dictionary_name.items()The items() method returns a new view of dictionary’s key and value pairs as tuples.
keys()dictionary_name.keys()The keys() method returns a new view consisting of all the keys in the dictionary.
pop()dictionary_name.pop(key[, default])The pop() method removes the key from the dictionary and returns its value. If the key is not present, then it returns the default value. If default is not given and the key is not in the dictionary, then it results in KeyError.
popitem()dictionary_name.popitem()The popitem() method removes and returns an arbitrary (key, value) tuple pair from the dictionary. If the dictionary is empty, then calling popitem() results in KeyError.
setdefault()dictionary_name.setdefault(key[,default])The setdefault() method returns a value for the key present in the dictionary. If the key is not present, then insert the key into the dictionary with a default value and return the default value. If key is present, default defaults to None, so that this method never raises a KeyError.
update()dictionary_name.update([other])The update() method updates the dictionary with the key:value pairs from other dictionary object and it returns None.
values()dictionary_name.values()The values() method returns a new view consisting of all the values in the dictionary.

For example,

>>> box_office_billion = {"avatar":2009, "titanic":1997, "starwars":2015, "harrypotter":2011, "avengers":2012}
>>> box_office_billion_fromkeys = box_office_billion.fromkeys(box_office_billion)
>>> box_office_billion_fromkeys
{'avatar': None, 'titanic': None, 'starwars': None, 'harrypotter': None, 'avengers': None}
>>> box_office_billion_fromkeys = box_office_billion.fromkeys(box_office_
billion, "billion_dollar")
>>> box_office_billion_fromkeys
{'avatar': 'billion_dollar', 'titanic': 'billion_dollar', 'starwars': 'billion_dollar', 'harrypotter': 'billion_dollar', 'avengers': 'billion_dollar'}
>>> print(box_office_billion.get("frozen"))
None
>>> box_office_billion.get("frozen",2013)
2013
>>> box_office_billion.keys()
dict_keys(['avatar', 'titanic', 'starwars', 'harrypotter', 'avengers'])
>>> box_office_billion.values()
dict_values([2009, 1997, 2015, 2011, 2012])
>>> box_office_billion.items()
dict_items([('avatar', 2009), ('titanic', 1997), ('starwars', 2015), ('harrypotter', 2011), ('avengers', 2012)])
>>> box_office_billion.update({"frozen":2013})
>>> box_office_billion
{'avatar': 2009, 'titanic': 1997, 'starwars': 2015, 'harrypotter': 2011, 'avengers': 2012, 'frozen': 2013}
>>> box_office_billion.setdefault("minions")
>>> box_office_billion
{'avatar': 2009, 'titanic': 1997, 'starwars': 2015, 'harrypotter': 2011, 'avengers': 2012, 'frozen': 2013, 'minions': None}
>>> box_office_billion.setdefault("ironman", 2013)
>>> box_office_billion
{'avatar': 2009, 'titanic': 1997, 'starwars': 2015, 'harrypotter': 2011, 'avengers': 2012, 'minions': None, 'ironman': 2013}
>>> box_office_billion.pop("avatar")
2009
>>> box_office_billion.popitem()
('ironman', 2013)
>>> box_office_billion.clear()
 {}

Populating and Traversing Dictionaries

Populating

One of the common ways of populating dictionaries is to start with an empty dictionary { }, then use the update() method to assign a value to the key using assignment operator. If the key does not exist, then the key:value pairs will be created automatically and added to the dictionary.

For example,

>>> countries = {}
>>> countries.update({"Asia":"India"})
>>> countries.update({"Europe":"Germany"})
>>> countries.update({"Africa":"Sudan"})
>>> countries
 {'Asia': 'India', 'Europe': 'Germany', 'Africa': 'Sudan'}

the dictionary can also be built using dictionary_name[key] = value syntax by adding key:value pairs to the dictionary.

Traversing

A for loop can be used to iterate over keys or values or key:value pairs in dictionaries. If you iterate over a dictionary using a for loop, then, by default, you will iterate over the keys. If you want to iterate over the values, use values() method and for iterating over the key:value pairs, specify the dictionary’s items() method explicitly. The dict_keys, dict_values, and dict_items data types returned by dictionary methods can be used in for loops to iterate over the keys or values or key:value pairs.

Program to Illustrate Traversing of key:value Pairs in Dictionaries

Using for Loop

currency = {"India": "Rupee", "USA": "Dollar", "Russia": "Ruble", "Japan": "Yen", 
"Germany": "Euro"}
def main():
print("List of Countries")
for key in currency.keys():
print(key)
print("List of Currencies in different Countries")
for value in currency.values():
print(value)
for key, value in currency.items():
print(f"'{key}' has a currency of type '{value}'")
if __name__ == "__main__":
main()
Shelton Coutinho
Shelton Coutinho
Articles: 13

Leave a Reply

Your email address will not be published. Required fields are marked *