Development

How to Add Items To A Python Dictionary

In this tutorial, we will learn one of the most fundamental operations when working with Python dictionaries. We will discuss how you can add an item to an existing Python dictionary.
Captain Salem 4 min read
How to Add Items To A Python Dictionary

a Python dictionary is a mutable data structure that stores an unordered collection of key-value pairs, where each key must be unique and immutable. Internally, it uses a hash table to provide efficient lookup and retrieval of values based on their associated keys.

Each key-value pair is stored as a separate entry in the hash table, where the key is hashed to a unique integer value that is used as an index into an array of "buckets". Each bucket contains a linked list of entries that have the same hash value, allowing multiple entries with different keys to be stored at the same index.

When a value is inserted or retrieved from a dictionary, Python computes the hash value of the key and uses it to look up the corresponding bucket in the hash table. It then traverses the linked list at that bucket to find the entry with the matching key.

Python Dictionary Fundamentals

As mentioned, a Python dictionary stores the information in a key-value pair format. This makes a dictionary an incredibly useful data structure especially when storing related information.

In Python, we define a Python dictionary using curly braces {}.

An example is as shown below:

database_ports = {
    "MySQL": 3306,
    "PostgreSQL": 5432,
    "Redis": 6379,
    "SQL Server": 1433,
    "MongoDB": 27017,
    "Elasticsearch": 9200
}

In the dictionary above, each database name is a key and its default port is the corresponding value. We can access the default port of a particular database by using its name as the key, like this:

>>> database_ports["MySQL"]
3306
>>> database_ports["Redis"]
6379

What if we want to modify the dictionary and add a new database name and port? Let us break it down.

Python Add Item to Dictionary

In Python, to add a new item to an existing dictionary, we need to use the index notation. Unlike Python lists and tuples, we do not have access to methods such as add(), insert(), or append().

Instead, we need to create a new index key which we can then use to store a new value to the existing dictionary.

Consider the syntax provided below:

dict_name[key] = value

Let us take the database_port dictionary we created earlier. Suppose we wish to add a new item for MS SQL Server and its corresponding port.

In that case, we can use the syntax as shown:

database_ports = {
    "MySQL": 3306,
    "PostgreSQL": 5432,
    "Redis": 6379,
    "SQL Server": 1433,
    "MongoDB": 27017,
    "Elasticsearch": 9200
}
database_ports["MS SQL Server"] = 1433

The above should add the new entry to the dictionary as shown in the print statement below:

>>> database_ports["MS SQL Server"] = 1433
>>> print(database_ports)
{'MySQL': 3306, 'PostgreSQL': 5432, 'Redis': 6379, 'SQL Server': 1433, 'MongoDB': 27017, 'Elasticsearch': 9200, 'MS SQL Server': 1433}

As you can see from the output above, the dictionary now contains the entry for MS SQL Server.

NOTE: It is good to keep in mind that data in a dictionary is unordered. Hence, adding a new item to a dictionary does not guarantee that the item will be appended to the beginning or the end of the dictionary.

How to Update a Dictionary Item

Python also allows us to update the item of a dictionary using a similar notation. For example, suppose we change the port of MySQL to port 3307.

An example is as shown:

>>> database_ports = {
...     "MySQL": 3306,
...     "PostgreSQL": 5432,
...     "Redis": 6379,
...     "SQL Server": 1433,
...     "MongoDB": 27017,
...     "Elasticsearch": 9200
... }

Updating the MySQL entry as shown;

>>> database_ports["MySQL"] = 3307

We can then print the dictionary as shown:

>>> print(database_ports)
{'MySQL': 3307, 'PostgreSQL': 5432, 'Redis': 6379, 'SQL Server': 1433, 'MongoDB': 27017, 'Elasticsearch': 9200, 'MS SQL Server': 1433}

As we can see, the value for the MySQL entry is set to 3307.

Conclusion

In this tutorial, we learned how we can add a new item to an existing Python dictionary by using the index notation. We also discovered that items in a Python dictionary are unordered, unlike a list and the unavailability of methods such as add(), append(), and 'insert() methods.

We hope you enjoyed this tutorial. If you have any feedback, comments or news, leave us a comment down below. You can also leave us a message on our contact page.

Check out these tutorials.

How to Resolve ImportError: No module named requests Error
In this post, we will explore various ways of fixing the ImportError: No module named requests when importing the requests library in Python.
How to get started with Python Sets
This article will help you get started with python set. You will learn how to create and manipulate them as well as work with sets operations.
SQL Data Types For MySQL and PostgreSQL
SQL supports various data types including Binary, Numeric, and Character data types. This guide explains each data type″s storage requirements, syntax, and provides examples.

If you enjoy our content, please consider buying us a coffee to support our work:

Share
Comments
More from GeekBits

Join us at GeekBits

Join our members and get a currated list of awesome articles each month.

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to GeekBits.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.