• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
NameHero® Blog

NameHero® Blog

Web Hosting Tips & Resources From NameHero

  • AI Agents
    • OpenClaw
    • Claude Code
    • n8n
    • Hermes Agent
    • Open WebUI
    • Docker
  • Hosting
    • Web Hosting
    • WordPress Hosting
    • WooCommerce Hosting
    • Enterprise Hosting
    • Email Hosting
    • HeroicGuard
    • GPU Hosting
    • Website Builder
  • VPS
    • Managed VPS
    • Unmanaged VPS
    • Flex VPS
  • Reseller
  • Gaming
  • Domains
  • Account
  • Blog Home
  • Categories
  • Authors

How to Initialize a Dictionary in Python

Bhagwad Park

Published on: April 24, 2024

Categories: Linux Command Line, VPS Hosting, Website Development 0

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.

Table of Contents
  • Initializing a Dictionary in Python
  • Accessing Dictionaries
  • Updating and Adding Dictionaries in Python
  • Why Can’t We Just Use Databases Instead of Dictionaries?
  • Dictionaries are Great for Working with Configuration Files
  • Conclusion

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:

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:

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': '[email protected]'},
'user2': {'name': 'Bob', 'age': 30, 'email': '[email protected]'}
}

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'] = '[email protected]'

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:

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.

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.

Bhagwad Park Profile Picture
Bhagwad Park

I’m a NameHero team member, and an expert on WordPress and web hosting. I’ve been in this industry since 2008. I’ve also developed apps on Android and have written extensive tutorials on managing Linux servers. You can contact me on my website WP-Tweaks.com!

Related Posts

How to Use Vim Search and Replace in Linux

The vim search and replace functionality in Linux consists of a series of very powerful tools - but also simple ones to get started easily.

Nmap Scan Types: How to Scan a Server’s Network

The "nmap" command allows you to scan a remote server and determine its network configuration. Here are the various nmap scan types.

How to Use Ufw to Open Port 80 in Linux

In Linux, particularly on Ubuntu system, here's how we can use ufw to open port 80. No need to mess with IPTables directly!

Using the “whois” Command – All you Need to Know

If you want to know about who owns a domain, or when it expires, then you need to use the "whois" command. Here's all you need to know.

Reader Interactions

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow & Subscribe

Exclusive promos, content and more!


Most Popular Posts

NameHero’s Recommended WordPress Plugin and Theme Setup

WordPress Hosting vs. Web Hosting – What’s The Difference?

How To Increase The InnoDB Buffer Pool Size

How To Fix A Stuck All-in-One WP Migration Import

How To Add A Subdomain In Cloudflare

Top Categories

  • WordPress
  • WordPress Tutorials
  • OpenClaw Hosting
  • Enterprise Hosting
  • WooCommerce
  • Web Hosting
  • Resellers
  • Website Security
  • Website Development
  • Website Performance
  • VPS Hosting
  • SEO Tips
  • Announcements
  • Domain Registration
NameHero

NameHero® proudly provides web hosting to over 40,000 customers with 99.9% uptime to over 750,000 websites.

  • Master Card
  • Visa
  • American Express
  • Discover
  • Paypal
Products
  • Web Hosting
  • Managed VPS Hosting
  • Unmanaged VPS Hosting
  • Flex VPS Hosting
  • WordPress Hosting
  • WooCommerce Hosting
  • Reseller Hosting
  • Enterprise Hosting
  • GPU Hosting
  • Email Hosting
  • HeroicGuard
  • Domains
  • Website Builder
  • AI Agent Hosting
Help & Support
  • NameHero Blog
  • NameHero Gaming Blog
  • Support
  • Help Center
  • Migrations
  • Affiliates
  • Gaming Affiliates
  • Call 1-855-984-6263
Company
  • About Us
  • Contact Sales
  • Reviews
  • Uptime
  • We're Hiring

Copyright © 2026 Name Hero, LLC. All rights reserved.
NameHero® is a registered trademark.

  • Privacy Policy
  • Terms of Use
  • Acceptable Use Policy
  • Payment Policy
  • DMCA