Open In App

Initialize Python Dictionary with Keys and Values

Last Updated : 23 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads