Initialize Python Dictionary with Keys and Values
Last Updated :
23 Jan, 2024
In this article, we will explore various methods for initializing Python dictionaries with keys and values. Initializing a dictionary is a fundamental operation in Python, and understanding different approaches can enhance your coding efficiency. We will discuss common techniques used to initialize Python dictionaries with keys and values, accompanied by illustrative code examples.
What is meant by a Dictionary with Keys and Values?
A dictionary in Python is a collection of unordered, mutable elements. Each element in a dictionary is a key-value pair, where each key must be unique. The key is used to index and access the corresponding value in the dictionary. In other words, a dictionary is a mapping of keys to values.
Initialize Python Dictionary with Keys and Values
Below, are the examples of the generally used method Initialize Python Dictionary with Keys and Values.
- Direct Initialize Dictionary
- Using For loop
- Using dict() Constructor
- Using dict.fromkeys()
- Using Dictionary Comprehension
Direct Initialize Dictionary
In this example, a Python dictionary named `direct_person` is directly initialized with keys "name" and "age," and its content along with type is printed.
Python3
# Direct method
direct_person = {'name': 'John', 'age': 25}
print("Direct method:", direct_person)
print("Type:", type(direct_person))
Direct method: {'name': 'John', 'age': 25}
Type: <class 'dict'>
Using For Loop
In this example, in below code Python dictionary named for_loop_person
is created using a for loop to iterate over a list of keys, which includes "name" and "age." Within the loop, it checks each key, assigning values accordingly—setting "Bob" for the "name" key and 22 for the "age" key.
Python3
# Using for loop
for_loop_person = {}
for key in ['name', 'age']:
if key == 'name':
for_loop_person[key] = 'Bob'
else:
for_loop_person[key] = 22
print("\nUsing for loop:", for_loop_person)
print("Type:", type(for_loop_person))
Output :
Using for loop: {'name': 'Bob', 'age': 22}
Type: <class 'dict'>
Using dict() Constructor
In this example , in below code `dict_constructor_person` dictionary is created using the `dict()` constructor with keys "name" and "age," assigned values 'Jane' and 30. The resulting dictionary is then printed, along with its type for quick reference.
Python3
# Using dict() Constructor
dict_constructor_person = dict(name='Jane', age=30)
print("\nUsing dict() Constructor:", dict_constructor_person)
print("Type:", type(dict_constructor_person))
Output :
Using dict() Constructor: {'name': 'Jane', 'age': 30}
Type: <class 'dict'>
Using dict.fromkeys()
In this example, in below code Python dictionary named `fromkeys_person` is formed using the `dict.fromkeys()` method. Keys are derived from the list `keys_person`, and all are assigned the same values from the list `values_person`. The resulting dictionary is then printed.
Python3
# Using dict.fromkeys()
keys_person = ['name', 'age']
values_person = ['Eva', 35]
fromkeys_person = dict.fromkeys(keys_person, values_person)
print("\nUsing dict.fromkeys():", fromkeys_person)
print("Type:", type(fromkeys_person))
Output :
Using dict.fromkeys(): {'name': ['Eva', 35], 'age': ['Eva', 35]}
Type: <class 'dict'>
Using Dictionary Comprehension
In this example, below code utilizes Dictionary Comprehension to create a Python dictionary named `comprehension_person`. It assigns the value 'Alice' for the key 'name' and 28 for the key 'age' within a concise one-liner. The resulting dictionary is printed.
Python3
# Using Dictionary Comprehension
comprehension_person = {key: 'Alice' if key == 'name' else 28 for key in ['name', 'age']}
print("\nUsing Dictionary Comprehension:", comprehension_person)
print("Type:", type(comprehension_person))
Output :
Using Dictionary Comprehension: {'name': 'Alice', 'age': 28}
Type: <class 'dict'>
Conclusion
In conclusion, initializing a Python dictionary with keys and values is a fundamental operation, crucial for organizing and accessing data efficiently. Various methods such as using curly braces, the dict()
constructor, dictionary comprehension, for loops, dict.fromkeys()
, and defaultdict
offer flexibility in creating dictionaries tailored to different scenarios.
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read