Python | Dictionary creation using list contents
Last Updated :
27 Apr, 2023
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
keys_list = ["key1", "key2"]
nested_name = ["Manjeet", "Nikhil"]
nested_age = [ 22 , 21 ]
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))
res = {key: { 'name' : name, 'age' : age} for key, name, age in
zip (keys_list, nested_name, nested_age)}
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
keys_list = ["key1", "key2"]
nested_name = ["Manjeet", "Nikhil"]
nested_age = [ 22 , 21 ]
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))
res = {val : {"name": nested_name[key], "age": nested_age[key]}
for key, val in enumerate (keys_list)}
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.
Similar Reads
Converting String Content to Dictionary - Python
In Python, a common requirement is to convert string content into a dictionary. For example, consider the string "{'a': 1, 'b': 2, 'c': 3}". The task is to convert this string into a dictionary like {'a': 1, 'b': 2, 'c': 3}. This article demonstrates several ways to achieve this in Python. Using ast
2 min read
Convert Dictionary to String List in Python
The task of converting a dictionary to a string list in Python involves transforming the key-value pairs of the dictionary into a formatted string and storing those strings in a list. For example, consider a dictionary d = {1: 'Mercedes', 2: 'Audi', 3: 'Porsche', 4: 'Lambo'}. Converting this to a st
3 min read
Python | Concatenate dictionary value lists
Sometimes, while working with dictionaries, we might have a problem in which we have lists as it's value and wish to have it cumulatively in single list by concatenation. This problem can occur in web development domain. Let's discuss certain ways in which this task can be performed. Method #1 : Usi
5 min read
Convert List Of Dictionary into String - Python
In Python, lists can contain multiple dictionaries, each holding key-value pairs. Sometimes, we need to convert a list of dictionaries into a single string. For example, given a list of dictionaries [{âaâ: 1, âbâ: 2}, {âcâ: 3, âdâ: 4}], we may want to convert it into a string that combines the conte
3 min read
Python | List of tuples to dictionary conversion
Interconversions are always required while coding in Python, also because of the expansion of Python as a prime language in the field of Data Science. This article discusses yet another problem that converts to dictionary and assigns keys as 1st element of tuple and rest as it's value. Let's discuss
3 min read
Convert a List to Dictionary Python
We are given a list we need to convert the list in dictionary. For example, we are given a list a=[10,20,30] we need to convert the list in dictionary so that the output should be a dictionary like {0: 10, 1: 20, 2: 30}. We can use methods like enumerate, zip to convert a list to dictionary in pytho
2 min read
Python | Clearing list as dictionary value
Clearing a list is a common problem and solution to it has been discussed many times. But sometimes, we don't have a native list but list is a value to dictionary key. Clearing it is not as easy as clearing an original list. Let's discuss certain ways in which this can be done. Method #1: Using loop
6 min read
Create a Dictionary with List Comprehension in Python
The task of creating a dictionary with list comprehension in Python involves iterating through a sequence and generating key-value pairs in a concise manner. For example, given two lists, keys = ["name", "age", "city"] and values = ["Alice", 25, "New York"], we can pair corresponding elements using
3 min read
Python | Dictionary to list of tuple conversion
Inter conversion between the datatypes is a problem that has many use cases and is usual subproblem in the bigger problem to solve. The conversion of tuple to dictionary has been discussed before. This article discusses a converse case in which one converts the dictionary to list of tuples as the wa
5 min read
Python Convert Dictionary to List of Values
Python has different types of built-in data structures to manage your data. A list is a collection of ordered items, whereas a dictionary is a key-value pair data. Both of them are unique in their own way. In this article, the dictionary is converted into a list of values in Python using various con
3 min read