Open In App

Python | Dictionary creation using list contents

Last Updated : 27 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes we need to handle the data coming in the list format and convert list into dictionary format. This particular problem is quite common while we deal with Machine Learning to give further inputs in changed formats. Let’s discuss certain ways in which this inter conversion happens. 

Method #1 : Using dictionary comprehension + zip() In this method, we use dictionary comprehension to perform the iteration and logic part, the binding of all the lists into one dictionary and with associated keys is done by zip function. 

Python3




# Python3 code to demonstrate
# Dictionary creation using list contents
# using Dictionary comprehension + zip()
 
# initializing list
keys_list = ["key1", "key2"]
nested_name = ["Manjeet", "Nikhil"]
nested_age = [22, 21]
 
# printing original lists
print("The original key list : " + str(keys_list))
print("The original nested name list : " + str(nested_name))
print("The original nested age list : " + str(nested_age))
 
# using Dictionary comprehension + zip()
# Dictionary creation using list contents
res = {key: {'name': name, 'age': age} for key, name, age in
              zip(keys_list, nested_name, nested_age)}
 
# print result
print("The dictionary after construction : " + str(res))


Output : 

The original key list : [‘key1’, ‘key2’] The original nested name list : [‘Manjeet’, ‘Nikhil’] The original nested age list : [22, 21] The dictionary after construction : {‘key1’: {‘age’: 22, ‘name’: ‘Manjeet’}, ‘key2’: {‘age’: 21, ‘name’: ‘Nikhil’}}

Time complexity: O(n), where n is the length of the test_list. The dictionary comprehension + zip() takes O(n) time
Auxiliary Space: O(n), where n is the number of elements in the list keys_list

  Method #2 : Using dictionary comprehension + enumerate() The similar task can be performed using enumerate function that was performed by the zip function. The dictionary comprehension performs the task similar as above. 

Python3




# Python3 code to demonstrate
# Dictionary creation using list contents
# using dictionary comprehension + enumerate()
 
# initializing list
keys_list = ["key1", "key2"]
nested_name = ["Manjeet", "Nikhil"]
nested_age = [22, 21]
 
# printing original lists
print("The original key list : " + str(keys_list))
print("The original nested name list : " + str(nested_name))
print("The original nested age list : " + str(nested_age))
 
# using dictionary comprehension + enumerate()
# Dictionary creation using list contents
res = {val : {"name": nested_name[key], "age": nested_age[key]}
       for key, val in enumerate(keys_list)}
 
# print result
print("The dictionary after construction : " + str(res))


Output : 

The original key list : [‘key1’, ‘key2’] The original nested name list : [‘Manjeet’, ‘Nikhil’] The original nested age list : [22, 21] The dictionary after construction : {‘key1’: {‘age’: 22, ‘name’: ‘Manjeet’}, ‘key2’: {‘age’: 21, ‘name’: ‘Nikhil’}}

Time complexity: O(n*n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), to store the keys and values in dictionary.

method#3: Loop and Zip Function

Approach

an empty dictionary is initialized. Using the zip function, a list of tuples containing values from the nested name and age lists is created. Then, using a for loop, the original key list is iterated through. For each key, a dictionary is created by popping the next tuple from the list of tuples created earlier. Finally, the new dictionary is added to the main dictionary with the key from the original key list. The main dictionary is then returned. This approach has a time complexity of O(n) and a space complexity of O(n), where n is the length of the original key list.

Algorithm

1. Initialize an empty dictionary.
2. Using the zip function, create a list of tuples containing the values from the nested name and age lists.
3. Iterate through the original key list using a for loop.
4. Create a dictionary for each key by using the pop function to get the next tuple from the list of tuples created in step 2.
5. Add the new dictionary to the main dictionary with the key from the original key list.
6. Return the main dictionary.

Python3




def create_dict_1(keys, names, ages):
    main_dict = {}
    values = list(zip(names, ages))
    for key in keys:
        nested_dict = {'name': values[0][0], 'age': values[0][1]}
        main_dict[key] = nested_dict
        values.pop(0)
    return main_dict
keys= ["key1", "key2"]
names= ["Manjeet", "Nikhil"]
ages= [22, 21]
print(create_dict_1(keys, names, ages))


Output

{'key1': {'name': 'Manjeet', 'age': 22}, 'key2': {'name': 'Nikhil', 'age': 21}}

Time complexity: O(n), where n is the length of the original key list.

Space complexity: O(n), where n is the length of the original key list.

METHOD 4:dictionary creation using for loop

APPROACH:

This approach uses a for loop to iterate over the indices of the key_list. For each index, a temporary dictionary temp_dict is created with the corresponding values from name_list and age_list. Finally, a new key-value pair is added to the result_dict with the key from key_list and the value of temp_dict. The method used here is called dictionary creation using for loop and is a common approach to create a dictionary from lists in Python.

ALGORITHM:

1.Create an empty dictionary result_dict.
2.Create a for loop to iterate through the length of the key list.
3.Inside the for loop, create a temporary dictionary temp_dict with the key ‘name’ and the value from the corresponding index of the nested name 4.list and with the key ‘age’ and the value from the corresponding index of the nested age list.
5.Add a new key-value pair to result_dict with the key from the corresponding index of the key list and the value of temp_dict.
6.Return result_dict.

Python3




key_list = ['key1', 'key2']
name_list = ['Manjeet', 'Nikhil']
age_list = [22, 21]
 
result_dict = {}
for i in range(len(key_list)):
    temp_dict = {'name': name_list[i], 'age': age_list[i]}
    result_dict[key_list[i]] = temp_dict
 
print(result_dict)


Output

{'key1': {'name': 'Manjeet', 'age': 22}, 'key2': {'name': 'Nikhil', 'age': 21}}

Time Complexity: O(n), where n is the length of the key list.
Auxiliary Space: O(n), as we are creating a new dictionary for each key-value pair.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads