Dictionaries are essential in Python since their introduction represented a significant advancement in programming. Before dictionaries, programming was far more difficult; you had to maintain all your data in lists or arrays and remember which indices were for which data, creating very mistake-prone procedures.
To locate values more rapidly, developers must sort lists and utilize binary search, and if the data is dynamic, developers must keep resorting. This process frequently resulted in very sluggish code that required further attention.
However, Python dictionaries solved this problem.
A dictionary in Python is a data type that stores variables in an unordered way where the values are mapped to a key and can be easily accessed using each item’s key. A key is an immutable element representing a value in a dictionary.
In this article, you will learn what dictionaries are in Python, their properties, the operations you can perform on them, and some built-in Python functions and methods for working with dictionaries.
Properties of a Python dictionary
There are some distinct behaviors a Python dictionary possesses that make it different from the other data structures. These properties include:
- Immutable dictionary keys
- An unordered collection of data
- Multiple data types for values
- Key data types can be a number, string, float, boolean, tuples, and built-in objects like class and functions
Additionally, dictionary keys must be unique. If there is a duplicate key defined in a dictionary, Python considers the last duplicate.
Python dictionary operations
Declaring a dictionary in Python
In Python, you can declare a dictionary by wrapping a sequence of value pairs (key and key-value in the format key: value
) separated by a comma in curly braces:
dict = {"first-key":1,"second-key":2}
You can also define an empty dictionary using empty curly braces as shown in the code snippet below:
dict = {}
Retrieving an item in a Python dictionary
To get the value of an item in a dictionary, enter the dictionary name with the item’s key in a square bracket:
# declared the dictionarydict = {"first-key":1,"second-key":2}# retrieved a value from the dictionarydict["first-key"]dict["second-key"]# your result should be 1 and 2
Here, you can access the value associated with the key name entered in the square bracket existing in the dictionary (dict
).
Inserting or updating a Python dictionary item
Inserting or updating an item in a dictionary is done using the append()
function. This function collects the key and value you want to insert in the dictionary before checking whether to insert it or use it to update values:
# declared the dictionarydict= {"first-key":1,"second-key":2}# inserting an item in the dictionary using append()dict["third-key"].append (3)# inserting an item in the dictionary without using append()dict["third-key"] = 3print(dict)# output item was created # {"first-key":1,"second-key":2, "third-key":3}
By inserting a value in the dictionary (dict
) using the append
function, the function registers the value entered in the bracket of the append
function using the key entered in the dictionary square brackets.
However, if the key specified already exists in the dictionary, Python only updates the value in the dictionary where appropriate:
# declared the dictionarydict= {"first-key":1,"second-key":2,"third-key":3}# updating an item in the dictionary using append()dict["third-key"].append (4) # updating an item in the dictionary without append()dict["third-key"] = 4 print(dict) # output value for key updated # {"first-key":1,"second-key":2, "third-key":4}
Since the key we entered into the square brackets already exists in the dictionary (dict
), the value associated with the key gets updated with the new value entered in the brackets of the append
function.
Deleting items in a Python dictionary
You can also remove an item from a dictionary by retrieving the item using the key the deleting the item using the del()
command, as seen in the code snippet below:
# declared the dictionarydict= {"first-key":1,"second-key":2,"third-key":3}#retrieve and delete an item in the dictionarydel(dict["third-key"]) print(dict) #output value for key updated {"first-key":1,"second-key":2}
Here, we deleted the item associated with the key specified in the square brackets from the dictionary using the del
function.
You can also delete the entire dictionary as seen in the code below:
dict= {"first-key":1,"second-key":2,"third-key":3}#delete entire dictionarydel(dict)
Looping through the items in a Python dictionary
Looping is available in Python to perform complex dictionary operations such as deleting all items with empty keys, retrieving data from nested dictionaries, inverting the values in the dictionary, and more.
Essentially, looping helps break down complex dictionary operations into steps, making them easier to accomplish.
Below is an example of utilizing looping to retrieve the items in a dictionary one by one:
# declaring the dictionarydict = { "brand": "Ford", "model": "Mustang", "year": 1964} #looping through items keys in the dictionaryfor x in thisdict: print(x)#output # brand # model # year #looping through item values in the dictionaryfor x in thisdict: print(thisdict[x])#output # Ford # Mustang # 1964
The first instance here describes how to access and print the item keys by looping through the dictionary, while the second instance describes how to access and print its values.
Nested dictionaries in Python
We stated earlier that we could insert any data type in the key-value of an item in a dictionary. However, a nested dictionary has another dictionary as a key-value in it.
You can use a nested dictionary when you must further associate a group of items as a whole using a specific key while associating each item with their keys. An example of this is associating an orange as citrus, a blueberry as a berry, then further grouping them as fruits.
Let’s see how to declare a nested dictionary with this example:
# declaring the nested dictionaryproducts = {"fruits":{"citrus":"orange","berry":"blueberry"}, "gadgets":{"laptop":"macbook","phone":"iphone"}}
In the code sample above, we can associate two dictionaries as items with specific keys in another dictionary. The dictionary covering the other dictionaries is called the parent dictionary.
In the next section, you’ll learn how to retrieve the items of a nested dictionary.
Retrieving an item in a Python nested dictionary
To retrieve an item from a nested dictionary, you must use two or more keys to get the key-value you need depending on the number of nests the dictionary contains.
More great articles from LogRocket:
- Don't miss a moment with The Replay, a curated newsletter from LogRocket
- Learn how LogRocket's Galileo cuts through the noise to proactively resolve issues in your app
- Use React's useEffect to optimize your application's performance
- Switch between multiple versions of Node
- Discover how to use the React children prop with TypeScript
- Explore creating a custom mouse cursor with CSS
- Advisory boards aren’t just for executives. Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
For example, if the parent dictionary contains one dictionary level, you need two keys to retrieve the item value. Below is an example showing how to retrieve a key-value using its keys:
# declaring the single nested dictionaryproducts = {"fruits":{"citrus":"orange","berry":"blueberry"}, "gadgets":{"laptop":"macbook","phone":"iphone"}}# get the laptop valueprint(products["gadgets"]["laptop"])print(products["fruits"]["citrus"])# output # macbook# orange
We only need two square brackets to retrieve the item values in the code sample above because the dictionary has only one nest.
In a situation where the dictionary has two nests, we must use three square brackets to retrieve the item values. Below is an example of a double nested dictionary:
# declaring the double nested dictionarycreatures = {"animal":{"mammal":{"human": "baby"}}, "plant":{"seeds":{"flower":"sun flower"}}}# get the laptop valueprint(creatures["animal"]["mammal"]["human"])print(creatures["plant"]["seeds"]["flower"])# output # baby# sun flower
Inserting or updating an item in a Python nested dictionary
To insert an item into a nested dictionary, you must assign or append a key and a value to the dictionary. If the item’s key already exists in the dictionary, then only the key-value updates. Otherwise, the item inserts into the dictionary.
Below is a code example showing how to insert or update an item in a nested dictionary:
# declaring the nested dictionaryproducts = {"fruits":{"citrus":"orange","berry":"blueberry"}, "gadgets":{"laptop":"macbook","phone":"iphone"}}# inserting or updating using appendnew_item={"shirt": "sleeves", "socks":"short socks"}products["clothes"].append(new_item)# inserting or updating without appendnew_item={"shirt": "sleeves", "socks":"short socks"}products["clothes"].append(new_item)print(products)# output# {"fruits":{"citrus":"orange","berry":"blueberry"}, "gadgets":{"laptop":"macbook","phone":"iphone"}, "clothes": {"shirt": "sleeves", "socks":"short socks"}}
Here, we declared a single nested dictionary named products
. To add items to the products
dictionary, we pass a new dictionary to the append
function. The new dictionary can then be added as an item in the products
parent dictionary.
Deleting an item from a Python nested dictionary
To delete an item from a nested dictionary, you must first retrieve the item using the key and then delete the item using the del()
method.
What differentiates this from the delete operation on your nonnested dictionary is that you can delete both dictionaries and values as items by passing a dictionary or key in the nested dictionary to the delete
function to be deleted.
Below is an example of deleting an item from a nested dictionary using Python. If we declare a products
nested dictionary, we can pass a dictionary to the delete
function, which deletes the dictionary from the nested dictionary:
# declaring the nested dictionaryproducts = {"fruits":{"citrus":"orange","berry":"blueberry"}, "gadgets":{"laptop":"macbook","phone":"iphone"}}# deleting the laptop item del(products["gadgets"]["laptop"])print(products)#output# products = {"fruits":{"citrus":"orange","berry":"blueberry"}, "gadgets":{"phone":"iphone"}}
Python dictionary functions
Python functions have specific uses that help ease the work on you as a developer because it enables you to build reusable code. Here are some built-in Python functions you can use to perform simple operations on a dictionary.
The cmp(dict1, dict2)
function
The cmp()
function compares two dictionaries to find out whether they have equal values. If their values are equal, then a response of 0
returns.
For instance, if we create four dictionaries, we can compare them using the cmp
function:
# declared 4 dictionariesdict1 = {"name":"john","age":18}dict2 = {"name":"Mary","age":12} dict3 = {"name":"Lisa","age":12}dict4 = {"name":"john","age":18}#comparing the dictionariesprint("value returned : %d" % cmp (dict1, dict2))print("value returned : %d" % cmp (dict2, dict3)) print("value returned : %d" % cmp (dict1, dict4)) # output # value returned: -1 # value returned: 1 # value returned: 0
Comparing dict1
and dict2
returns an output of -1
because there is nothing similar within them.
However, comparing dict2
and dict3
returns a result of 1
because they have the same age values and comparing dict1
and dict4
returns an output of 0
because they have all the same values, as mentioned previously.
The len(dict)
function
The len()
function gets the length of the dictionary passed in it and returns the total number of items in a list. This statement implies that if a dictionary has three items, then its length is 3
.
You can use this function to find the length of any dictionary:
# declared dictionarydict = {"name":"john","age":18, "weight": "65kg"}# get the length of dictprint("The length of dict is: %d" % len(dict))#output# The length of dict is: 3
The str(dict)
function
The str(dict)
function can get the printable string representation of a dictionary passed in it. You can use this when you want to print the dictionary as a string:
# declared dictionarydict = {"name":"john","age":18, "weight": "65kg"}# get the str representation of dictprint("The string equivalent of dict is: %s" % str(dict))#output# The string equivalent of dict is {'name': 'john', 'age': 18, 'weight': '65kg'}
The type()
function
The type()
function can return the data type of a variable passed in it. If you pass a dictionary in the type()
function, it will return a dict
data type. You can use this function to know the data type of any variable:
# declare dictionarydict = {"name":"john","age":18, "weight": "65kg"}# return the data typeprint("Data Type : %s" % type (dict))# output# Data Type: <type 'dict'>
Python dictionary methods
Python methods, similar to functions we saw earlier, allow you to reuse and perform operations prebuilt for you. Here are some built-in Python methods you can use to perform operations on a dictionary.
The dict.clear()
method
The dict.clear()
method removes all the items from the dictionary to return an empty dictionary. You can use this when you want to empty your dictionary quickly to get a clean slate. Below is an example of using the clear()
method:
# declare the dictionarydict = {'Name': 'Andrew', 'Age': 7};# delete all items in the dictionarydict.clear()print("Dictionary : %s" % str(dict))# output # Dictionary : {}
The dict.copy()
method
The copy()
method gets a copy of the dictionary passed to it. You can use it when you don’t want to create a dictionary from scratch. It also reduces the stress of copying item by item from the current dictionary to a new dictionary:
# declare the dictionarydict1 = {'Name': 'Andrew', 'Age': 7}# make a copy of the dictionarydict2 = dict1.copy()print("New Dictionary : %s" % str(dict2))# output # New Dictionary : {'Name': 'Andrew', 'Age': 7}
By creating a dictionary (dict1
), then making a copy in dict2
using the copy
method, you can see both dictionaries have the same values from the output.
The dict.fromkey()
method
The dict.fromkey()
method can create a dictionary from a sequence of values. When creating a dictionary, each value in the sequence becomes a key in the dictionary.
You can use this method to create a dictionary using keys you don’t have the values for yet. This is done following the dict.fromkeys(seq[, value])
syntax:
# create a sequenceseq = ('name', 'age', 'sex')#create a dictionary from the sequencedict = dict.fromkeys(seq)print("New Dictionary : %s" % str(dict))dict = dict.fromkeys(seq, 10)print("New Dictionary : %s" % str(dict))#output# New Dictionary : {'age': None, 'name': None, 'sex': None}# New Dictionary : {'age': 10, 'name': 10, 'sex': 10}
In the code sample above, we can create dict
from a variable containing a sequence of keys (seq
) using the fromkeys()
method. From the output of dict
, we can see that the keys exist in the dictionaries, but the values are set to none
.
The dict.has_key()
method
The has_keys()
method checks whether a key exists in the dictionary passed to it. You can also use it to verify whether a key exists in a dictionary easily. It then returns a boolean value (either True
or False
).
Here, we can declare a variable (dict
) and check whether the keys Age
and Sex
exist in it using the has_key method:
# declare the dictionarydict = {'Name': 'Andrew', 'Age': 13}# check for key in the dictionaryprint("Value : %s" % dict.has_key('Age'))print("Value : %s" % dict.has_key('Sex'))#Output# Value : True# Value : False
When checking the first key, Age
returns true
, which means the item exists in the dictionary. While checking for the second key, Sex
returns false
, meaning the item doesn’t exist in the dictionary.
The dict.items()
method
The items()
method gets a list of a dictionary’s keys and values arranged in tuple pairs. We can use this to get a list of the keys and values of all items in your dictionary.
We can do this by creating a dictionary (dict
) and printing all the keys and values of the items in it side-by-side in a list using the items
method:
# declare the dictionarydict = {'Name': 'Molly', 'Age': 7}# get items in the dictionaryprint("Value : %s" % dict.items())# output# Value : [('Age', 7), ('Name', 'Molly')]
The dict.keys()
method
The keys()
method returns a list of all existing keys in the dictionary. You can use it to get a list of all the keys in a dictionary to perform any further operations you want:
dict = {'Name': 'Andrew', 'Age': 23}print("Value : %s" % dict.keys())#output# Value : ['Age', 'Name']
The dict.update(dict2)
method
If the values don’t exist, the update()
method inserts a dictionary’s item into another dictionary. Otherwise, it updates the values where appropriate.
You can use the update
method as an alternative to the append
function. However, the update
method can update items in a dictionary using another dictionary:
# declare the dictionariesdict = {'Name': 'Molly', 'Age': 7}dict2 = {'Sex': 'female' }# update dict with dict2 itemsdict.update(dict2)print("Value : %s" % dict)# output# Value : {'Name': 'Molly', 'Age': 7, 'Sex': 'female'}
By creating two dictionaries, dict
and dict2
, we can update the values of dict
with the values of dict2
using the update
method. The output shows that dict
now contains dict2
items, meaning it didn’t exist in dict
before running the update
method.
The dict.values()
method
The values()
method returns a list of values existing in a dictionary without their keys. You can use this method to get only the values in your dictionary without worrying about accessing them with their keys:
# declare dictionarydict = {'Name': 'Zubair', 'Age': 7}# get all item valuesprint("Value : %s" % dict.values())# output# Value : [7, 'Zubair']
Conclusion
Through this article, we learned how to declare a dictionary in Python, manage its data, and perform some operations on it. In addition, we learned about nested dictionaries and how they work.
I hope this article helps you become a better Python developer. Happy coding!
Get set up with LogRocket's modern error tracking in minutes:
- Visit https://logrocket.com/signup/ to getan app ID
Install LogRocket via npm or script tag.
LogRocket.init()
must be called client-side, notserver-side- npm
- Script tag
$ npm i --save logrocket // Code:import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML:<script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script><script>window.LogRocket && window.LogRocket.init('app/id');</script>
- (Optional) Install plugins for deeper integrations with your stack:
- Redux middleware
- NgRx middleware
- Vuex plugin
Get started now