How to Initialize a Dictionary with Keys in Python?

Rate this post

Summary: The most Pythonic approach to initialize a dictionary with keys is to use the dict.fromkeys(key, None) dictionary method, which accepts each item from the given list as a key and associates None to each key as a value.


Problem Formulation: Given a list containing employee IDs as items within it. How will you create a dictionary having only keys using the items of the given list (employee IDs) as the keys?

Example:

Given list:  
# list of employee IDs --> keys
emp_id = [10946, 20480, 30856]

Expected Output:
{10946: None, 20480: None, 30856: None}

Without further delay, let us dive into the numerous solutions to our mission-critical question.

📹Video Walkthrough

Method 1: The Basic Approach

Approach: Use a for loop to iterate across each element in the given list one by one. In each iteration, assign None as the value to the key such that the key represents each element of the given list.

Code:

# list of employee IDs --> keys
emp_id = [10946, 20480, 30856]
record = {}
# iterate through list and assign None Values to the keys
for i in emp_id:
    record[i] = None
# display dictionary
print(record)

Output:

{10946: None, 20480: None, 30856: None}

Method 2: The Pythonic Solution Using fromkeys

The best and most Pythonic way to solve the given problem is to use the dictionary method fromkeys to assign the keys from the list into the dictionary.

fromkeys() is a dictionary method that returns a dictionary based on specified keys and values passed within it as parameters.

Syntax: dict.fromkeys(keys, value)
➡ keys is a required parameter that represents an iterable containing the keys of the new dictionary.
➡ value is an optional parameter which represents the values for all the keys in the new dictionary. By default, it is None.

Example: The following code snippet reveals how we can initialize a dictionary with keys from a tuple and associate 0 as a value to each key.

k = ('key_1', 'key_2', 'key_3')
my_dictionary = dict.fromkeys(k, 0)
print(my_dictionary)

# OUTPUT: {'key_1': 0, 'key_2': 0, 'key_3': 0}

Solution: Let us now dive into the solution to the given problem and visualize how to use the fromkeys() function to initialize a dictionary with only keys.

# list of employee IDs --> keys
emp_id = [10946, 20480, 30856]
# Using fromkeys
record = dict.fromkeys(emp_id, None)
# display dictionary
print(record)

Output:

{10946: None, 20480: None, 30856: None}

#Note: Even if you dont specify the value as None; by default it will be considered as None.

Method 3: Using Dictionary Comprehension

Another workaround to initialize a dictionary with keys is to simply use dictionary comprehension. Before we dive into the solution, let’s have a quick recap of what dictionary comprehensions are.

Dictionary Comprehension is a concise and memory-efficient way to create and initialize dictionaries in one line of Python code. It consists of two parts: expression and context. The expression defines how to map keys to values. The context loops over an iterable using a single-line for loop and defines which (key, value) pairs to include in the new dictionary.

Video Tutorial:

Approach: The idea is to use a dictionary comprehension such that the expression represents the key-value pairs to be inserted in the dictionary.

  • Here, the expression is key: None, where the key represents each item from the given list and serves as the keys of the dictionary, while None is the value associated with each key.
  • The context variable key represents each item in the given list emp_id such that each item can be acquired as a key for the dictionary by iterating across all the elements in the given list.

Code:

# list of employee IDs --> keys
emp_id = [10946, 20480, 30856]
# Using fromkeys
record = {key: None for key in emp_id }
# display dictionary
print(record)

Output:

{10946: None, 20480: None, 30856: None}

Method 4: Using zip

Approach: Call the zip(emp_id, [None]*len(emp_id)) method to create a zip object. This zip object will be created using the following iterables:

  • Iterable 1 represents the given list emp_id, i.e., [10946, 20480, 30856]
  • Iterable 2 represents a list having None as items such that the number of items/ None values within the list will be equal to the length of the list, i.e., [None, None, None]

Thus, when you zip these two iterables, it will create a zip object by combining the i-th from each iterable. This means each item from the given list will be mapped to the None value from the second iterable. Finally, to derive a dictionary out of this zip object, you must convert it to a dictionary using the dict constructor.

Code:

# list of employee IDs --> keys
emp_id = [10946, 20480, 30856]
# Using zip
record = dict(zip(emp_id, [None]*len(emp_id)))
# display dictionary
print(record)

Output:

{10946: None, 20480: None, 30856: None}

A quick recap to zip: The zip() function takes an arbitrary number of iterables and aggregates them to a single iterable, a zip object. It combines the i-th values of each iterable argument into a tuple. Hence, if you pass two iterables, each tuple will contain two values. If you pass three iterables, each tuple will contain three values. For example, zip together lists [1, 2, 3] and [4, 5, 6] to [(1,4), (2,5), (3,6)].

Video Tutorial:

Conclusion

Well! We unearthed four different ways of initializing a dictionary with only keys in Python in this article. To sum things up, the most Pythonic approach to do so would be to use the dict.fromkeys function. However, feel free to use any of the above-mentioned approaches that suit your requirements.

I hope this article has helped you. Please subscribe and stay tuned for more interesting tutorials. Happy learning! 🙂


But before we move on, I’m excited to present you my new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Link: https://nostarch.com/pythononeliners