Connect with us

Website Tutorials

How to Initialize a Dictionary in Python

Published

on

How to Initialize a Dictionary in Python

In Python, we have a data structure called a “dictionary” that’s used to hold key/value pairs. Thanks to the flexibility of data types in Python, these values can also include lists, which means you can associate more than one value with a single key if you want. You can also associate another dictionary with a value and create nested dictionaries. You can also create your own data types to store as values.

Thanks to this flexibility, dictionaries in Python have a wide range of functions. In this article, I’ll show you how to initialize a dictionary and some more advanced use cases. We’ll also discuss if it’s useful to use a dictionary instead of a database, and thereby address some of the shortcomings of dictionaries, and some examples of where dictionaries are useful.

Initializing a Dictionary in Python

There are many ways to initialize a dictionary in Python, depending on whether you want to create an empty dictionary or one pre-filled with values that you specify. For example, to just create a new dictionary, we can use:

my_dict = {}

The two curly brackets {} signify a dictionary. You can also initialize a dictionary like this:

another_dict = dict()

The “dict()” function is a constructor that we can use to either create an empty dictionary or one pre-filled with data. For example, we can use it to create a dictionary like this:

Advertisement
my_dict = {'name': 'Alice', 'age': 25}

The above dictionary has two items – name and age. These are “keys”. Each key is associated with a value. So if we retrieve the “name” key, the value assigned to it is “Alice”, and the corresponding value is true for “age”.

Instead of initializing with key/value pairs as above, you can so initialize a dictionary with tuples:

my_dict = dict([('name', 'Alice'), ('age', 25)])

The above code consists of a series of “tuples”. These are ordered elements that can’t be modified once created. As you can see above, we can use the “dict()” constructor to pass the tuples, and the function will do the hard work of converting them into a dictionary data structure.

Since a dictionary can also hold other dictionaries, we can use this structure to create a database of people, with each entry being a separate dictionary for each person.

Accessing Dictionaries

One of the benefits of using a dictionary, as opposed to other data types like a list of key/value pairs, is that you can access the elements of a dictionary individually without having to iterate over the entire set of elements. So, for example, if you want to get the “name” element, you can use:

Advertisement
print(my_dict['name'])

This generates the following output:

Accessing the Dictionary Elements
Accessing the Dictionary Elements

So we can use a single key to access its value.

Now let’s say that we want to hold the data of another person – Bob. In this case, we can create a “dictionary of dictionaries” like this:

user_profiles = {
    'user1': {'name': 'Alice', 'age': 25, 'email': 'alice@example.com'},
    'user2': {'name': 'Bob', 'age': 30, 'email': 'bob@example.com'}
}

print(user_profiles['user2']['age'])

In the above example, we have created a separate dictionary for Alice and Bob, and stored both of them in an “outer dictionary” called “user_profiles”. Now to access the Bob’s age, we just need to specify the appropriate key as shown above:

Accessing a Dictionary of Dictionaries
Accessing a Dictionary of Dictionaries

And, as expected, we get Bob’s age. You can see how useful this is, as you can create an unlimited number of key/value pairs for each person, with each key describing a certain attribute, and then extend that to as many people as you want. it’s this flexibility that makes dictionaries so useful since you can use it to describe any collection of objects.

Updating and Adding Dictionaries in Python

Unlike immutable tuples, you can modify dictionary entries as shown here.

my_dict['email'] = 'alice@example.com'

In the above code sample, I’m creating a new dictionary entry in the dictionary I’ve already created. Previously I had saved the name and age, and now I’m adding the e-mail as well. If this was a data structure like a tuple, it wouldn’t be possible. We can print the email as shown here:

Advertisement
Adding the email to the Dictionary
Adding the email to the Dictionary

Using the same syntax, we can modify dictionary entries. Let’s say time has passed, and we need to increase Alice’s age. The code for that would be:

my_dict['age'] = 26

Now when you print the age, it will show as 26 instead of 25.

Why Can’t We Just Use Databases Instead of Dictionaries?

If you have some experience programming, dictionaries sound a lot like tables in a database. After all, when we think of storing easily retrievable information about a person like their name, age, etc, the first solution is to create a database with a table called “People” or something and use that as a storage mechanism. Tables are easy to create, and manage, and using SQL, we can retrieve the data in an infinite variety of ways – definitely more flexible than dictionaries.

So why use dictionaries at all? Shouldn’t we use tables for everything?

The reason is that dictionaries give you a quick and easy way to access data without the hassle of connecting to a database, creating a table, and performing all the associated operations. The data in a table isn’t meant to be stored for the long term, and it lasts only as long as the Python program is running.

When you connect a program to a database, it takes on additional dimensions. You have to define the database schema, create the table after determining its datatype, and seriously commit to thinking through all the possibilities and complications associated with a database. It’s not something you create on a whim. Not to mention, you then have to install the RDBMS software and everything.

Advertisement

With a dictionary, you don’t have to think about any of this. If you need some structured data in a key/value format, you can make it in seconds and never have to worry about anything else.

Dictionaries are Great for Working with Configuration Files

An excellent use-case for dictionaries is when you want to load configuration files into memory so you can read the data for running your application. These are situations where you just need quick access to data that’s already stored in a file. You can see why a database for this situation would be overkill.

Instead, you can read the configuration file which anyway, will consist of key/value pairs into a dictionary – an action that should take a minuscule amount of time, given how small configuration files usually are, and then just read the values by calling the keys whenever necessary inside your program.

When the program is about to close, you can simply dump the contents of the dictionary back into the configuration file to save anything that might have changed. Or, if you want, you can save it periodically, or whenever a value gets updated.

Conclusion

Dictionaries in Python are extremely easy to initialize and use. At first glance, it might appear that databases will serve the same purpose, but the ease of use of dictionaries gives them the edge when the data doesn’t require such a structured approach and is more “ad hoc”. You can even store dictionaries within dictionaries, allowing you to create complex data structures that are easy to work with.

Advertisement

Stephen Oduntan is the founder and CEO of SirsteveHQ, one of the fastest growing independent web hosts in Nigeria. Stephen has been working online since 2010 and has over a decade experience in Internet Entrepreneurship.

Continue Reading
Advertisement
Comments

Trending

Copyright © 2024 SirsteveHQ. All Rights Reserved.