Python – Assign list items to Dictionary
Last Updated :
19 Apr, 2023
Sometimes, while working with Python dictionaries, we can have a problem in which we need to assign list elements as a new key in dictionary. This task can occur in web development domain. Lets discuss certain ways in which this task can be performed.
Method #1 : Using zip() + loop The combination of above functions can be used to solve this problem. In this, we combine list elements with dictionary using zip() and loop is used to combine iteration logic.
Python3
test_list = [{'Gfg': 1, 'id': 2},
{'Gfg': 4, 'id': 4}]
print("The original list is : " + str(test_list))
new_key = 'best'
add_list = [12, 2]
res = []
for sub, val in zip(test_list, add_list):
sub[new_key] = val
res.append(sub)
print("The modified dictionary : " + str(res))
test_list = [{'Gfg': 1, 'id': 2},
{'Gfg': 4, 'id': 4}]
print("The original list is : " + str(test_list))
new_key = 'best'
add_list = [12, 2]
res = []
for sub, val in zip(test_list, add_list):
sub[new_key] = val
res.append(sub)
print("The modified dictionary : " + str(res))
|
Output :
The original list is : [{‘Gfg’: 1, ‘id’: 2}, {‘Gfg’: 4, ‘id’: 4}] The modified dictionary : [{‘best’: 12, ‘Gfg’: 1, ‘id’: 2}, {‘best’: 2, ‘Gfg’: 4, ‘id’: 4}]
Time complexity: O(n), where n is the length of the input list. The loop iterates over each element of the input list once.
Auxiliary Space: O(n), where n is the length of the input list. The space used by the output list ‘res’ is proportional to the length of the input list. Additionally, a constant amount of space is used for initializing variables like ‘new_key’ and ‘add_list’.
Method #2 : Using list comprehension + zip() The combination of above functions can be used to solve this problem. In this, we perform the iteration of elements using list comprehension and hence a shorthand.
Python3
test_list = [{'Gfg': 1, 'id': 2},
{'Gfg': 4, 'id': 4}]
print("The original list is : " + str(test_list))
new_key = 'best'
add_list = [12, 2]
res = [{**sub, new_key: ele} for sub, ele in zip(test_list, add_list)]
print("The modified dictionary : " + str(res))
|
Output :
The original list is : [{‘Gfg’: 1, ‘id’: 2}, {‘Gfg’: 4, ‘id’: 4}] The modified dictionary : [{‘best’: 12, ‘Gfg’: 1, ‘id’: 2}, {‘best’: 2, ‘Gfg’: 4, ‘id’: 4}]
The time complexity of the given code is O(n), where n is the length of the input list test_list.
The space complexity of the code is O(n), where n is the length of the input list test_list
Method #3 : Using for loop and update() method
Python3
test_list = [{'Gfg' : 1, 'id' : 2 },
{'Gfg' : 4, 'id' : 4 }]
print("The original list is : " + str(test_list))
new_key = 'best'
add_list = [12, 2]
x=[]
for i in add_list:
d=dict()
d[new_key]=i
x.append(d)
print(x)
for i in range(0,len(test_list)):
test_list[i].update(x[i])
print("The modified dictionary : " + str(test_list))
|
Output
The original list is : [{'Gfg': 1, 'id': 2}, {'Gfg': 4, 'id': 4}]
[{'best': 12}, {'best': 2}]
The modified dictionary : [{'Gfg': 1, 'id': 2, 'best': 12}, {'Gfg': 4, 'id': 4, 'best': 2}]
Time Complexity: O(n) where n is the number of elements in the dictionary. The loop and update() method is used to perform the task and it takes O(n) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the dictionary.
Method #4: Using dictionary comprehension and zip()
This method uses dictionary comprehension and the zip() function to iterate over both test_list and add_list simultaneously. The ** operator is used to unpack each dictionary in test_list, and then the new key-value pair is added using new_key and the corresponding value from add_list. The resulting list of dictionaries is stored in result.
Python3
test_list = [{'Gfg': 1, 'id': 2}, {'Gfg': 4, 'id': 4}]
new_key = 'best'
add_list = [12, 2]
result = [{**d, new_key: i} for d, i in zip(test_list, add_list)]
print("The modified dictionary : " + str(result))
|
Output
The modified dictionary : [{'Gfg': 1, 'id': 2, 'best': 12}, {'Gfg': 4, 'id': 4, 'best': 2}]
Time Complexity: O(n), where n is the length of the test_list.
Auxiliary Space: O(n), where n is the length of the test_list.
Method #5:Using map() and filter()
Algorithm
1. Initialize test_list, new_key, and add_list.
2. Use filter() to construct a list of dictionaries, with each dictionary having a single key new_key and a value from the add_list. Store the resulting list in res.
3. Use map() to iterate over each dictionary ele in test_list.
4. Use update() to assign the items in the corresponding dictionary from res to the dictionary ele.
5. Print the resulting modified test_list.
Python3
test_list = [{'Gfg': 1, 'id': 2},
{'Gfg': 4, 'id': 4}]
print("The original list is : " + str(test_list))
new_key = 'best'
add_list = [12, 2]
res = [dict(zip([new_key], [val])) for val in add_list]
list(map(lambda ele: ele.update(res.pop(0)), test_list))
print("The modified dictionary : " + str(test_list))
|
Output
The original list is : [{'Gfg': 1, 'id': 2}, {'Gfg': 4, 'id': 4}]
The modified dictionary : [{'Gfg': 1, 'id': 2, 'best': 12}, {'Gfg': 4, 'id': 4, 'best': 2}]
Time Complexity: O(N)
Creating the list of dictionaries using filter() takes O(N) time, where N is the length of the add_list.
The map() function iterates over each dictionary in test_list, and the update() method takes O(1) time to assign a new item to a dictionary. Thus, the time complexity for updating each dictionary in test_list is O(1).
Therefore, the overall time complexity of this algorithm is O(N), where N is the length of the add_list.
Auxiliary Space: O(N)
The space complexity of this algorithm depends on the size of the input lists and the number of dictionaries in test_list.
The filter() method creates a new list of dictionaries with a size equal to the length of add_list, so the space complexity is O(N), where N is the length of the add_list.
The map() function creates a new iterator object with a size equal to the length of test_list, so the space complexity is also O(N), where N is the length of test_list.
Method 6: Using a list comprehension with enumerate() function:
- Initialize the original list test_list, key new_key and list of values add_list.
- Use a list comprehension to iterate over the list test_list and enumerate function to get the current index and the current sub-dictionary.
- Use dictionary unpacking with **sub to create a new dictionary including the current sub-dictionary and the new key-value pair new_key: add_list[i] (with i being the current index).
- The list comprehension creates a new list of dictionaries with the updated values.
Python3
test_list = [{'Gfg': 1, 'id': 2},
{'Gfg': 4, 'id': 4}]
print("The original list is : " + str(test_list))
new_key = 'best'
add_list = [12, 2]
res = [ { **sub, new_key: add_list[i] } for i, sub in enumerate(test_list)]
print("The modified dictionary : " + str(res))
|
Output
The original list is : [{'Gfg': 1, 'id': 2}, {'Gfg': 4, 'id': 4}]
The modified dictionary : [{'Gfg': 1, 'id': 2, 'best': 12}, {'Gfg': 4, 'id': 4, 'best': 2}]
Time complexity: O(n), where n is the number of dictionaries in test_list.
Auxiliary space: O(n), where n is the number of dictionaries in test_list.
Method#7: Using Recursive method.
This function takes three arguments: test_list is the list of dictionaries to modify, new_key is the key to add to each dictionary, and add_list is the list of items to assign to the new_key. The function returns a new list of dictionaries with the new_key assigned to each dictionary.
The function works recursively by processing one sub-list at a time. The base case is when test_list is empty, in which case an empty list is returned. Otherwise, the function modifies the first dictionary in test_list by assigning the first item in add_list to the new_key, and then recursively calls itself with the remainder of test_list and add_list. The function concatenates the modified dictionary with the result of the recursive call, and returns the new list.
Python3
def assign_list_items_to_dict(test_list, new_key, add_list):
if not test_list:
return []
sub = test_list[0]
sub[new_key] = add_list[0]
return [sub] + assign_list_items_to_dict(test_list[1:], new_key, add_list[1:])
test_list = [{'Gfg': 1, 'id': 2},
{'Gfg': 4, 'id': 4}]
print("The original list is : " + str(test_list))
new_key = 'best'
add_list = [12, 2]
res = assign_list_items_to_dict(test_list, new_key, add_list)
print("The modified dictionary : " + str(res))
|
Output
The original list is : [{'Gfg': 1, 'id': 2}, {'Gfg': 4, 'id': 4}]
The modified dictionary : [{'Gfg': 1, 'id': 2, 'best': 12}, {'Gfg': 4, 'id': 4, 'best': 2}]
The time and space complexities of the recursive method for assigning list items to a dictionary depend on the size of the input list.
In the best case scenario, the input list is empty, and the function simply returns the input dictionary. In this case, the time complexity is O(1), and the space complexity is also O(1).
In the worst case scenario, the input list has n elements. In this case, the function needs to iterate through each element in the list and perform a constant number of operations (updating the dictionary). Therefore, the time complexity is O(n), and the space complexity is O(n) as well, since the recursive calls create n new dictionaries on the call stack.
Overall, the time and space complexities of the recursive method are linear with respect to
Similar Reads
Python - Assign list items to Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to assign list elements as a new key in dictionary. This task can occur in web development domain. Lets discuss certain ways in which this task can be performed. Method #1 : Using zip() + loop The combination o
10 min read
Python - Accessing Items in Lists Within Dictionary
Given a dictionary with values as a list, the task is to write a python program that can access list value items within this dictionary. Method 1: Manually accessing the items in the list This is a straightforward method, where the key from which the values have to be extracted is passed along with
5 min read
Dictionary keys as a list in Python
In Python, we will encounter some situations where we need to extract the keys from a dictionary as a list. In this article, we will explore various easy and efficient methods to achieve this. Using list() The simplest and most efficient way to convert dictionary keys to lists is by using a built-in
2 min read
Appending a dictionary to a list in Python
Appending a dictionary allows us to expand a list by including a dictionary as a new element. For example, when building a collection of records or datasets, appending dictionaries to a list can help in managing data efficiently. Let's explore different ways in which we can append a dictionary to a
3 min read
Python - Convert Index Dictionary to List
Sometimes, while working with Python dictionaries, we can have a problem in which we have keys mapped with values, where keys represent list index where value has to be placed. This kind of problem can have application in all data domains such as web development. Let's discuss certain ways in which
3 min read
Convert a Dictionary to a List in Python
In Python, dictionaries and lists are important data structures. Dictionaries hold pairs of keys and values, while lists are groups of elements arranged in a specific order. Sometimes, you might want to change a dictionary into a list, and Python offers various ways to do this. How to Convert a Dict
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
Convert List of Lists to Dictionary - Python
We are given list of lists we need to convert it to python . For example we are given a list of lists a = [["a", 1], ["b", 2], ["c", 3]] we need to convert the list in dictionary so that the output becomes {'a': 1, 'b': 2, 'c': 3}. Using Dictionary ComprehensionUsing dictionary comprehension, we ite
3 min read
Adding Items to a Dictionary in a Loop in Python
The task of adding items to a dictionary in a loop in Python involves iterating over a collection of keys and values and adding them to an existing dictionary. This process is useful when we need to dynamically build or update a dictionary, especially when dealing with large datasets or generating k
3 min read
Python - Assign values to initialized dictionary keys
Sometimes, while working with python dictionaries, we can have a problem in which we need to initialize dictionary keys with values. We save a mesh of keys to be initialized. This usually happens during web development while working with JSON data. Lets discuss certain ways in which this task can be
5 min read
Python - Flatten Dictionary with List
Given a list and dictionary, flatten dictionary with keys and values at position of available element of key in list. Input : test_list = ["Gfg", "is", "Best", "For", "Geeks"], subs_dict = {"Gfg" : 7} Output : ['Gfg', 7, 'is', 'Best', 'For', 'Geeks'] Explanation : "Gfg" is replaced, followed by its
4 min read
How to Print a Dictionary in Python
Python Dictionaries are the form of data structures that allow us to store and retrieve the key-value pairs properly. While working with dictionaries, it is important to print the contents of the dictionary for analysis or debugging. Example: Using print Function [GFGTABS] Python # input dictionary
3 min read
Python | Priority key assignment in dictionary
Sometimes, while working with dictionaries, we have an application in which we need to assign a variable with a single value that would be from any of given keys, whichever occurs first in priority. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop This task can
4 min read
Python - Change type of key in Dictionary list
Sometimes, while working with data, we can have a problem in which we require to change the type of particular keys' value in list of dictionary. This kind of problem can have application in data domains. Lets discuss certain ways in which this task can be performed. Input : test_list = [{'gfg': 9,
6 min read
Convert Dictionary to String List in Python
Dictionaries represent a data structure for the key-value pairs in Python. A lot of times, one needs to transform a dictionary into a string list to print logs or perform data manipulations. In this article, the dictionary data type is converted to a string list in Python using many concepts and met
2 min read
Convert Nested Dictionary to List in Python
In this article, we’ll explore several methods to Convert Nested Dictionaries to a List in Python. List comprehension is the fastest and most concise way to convert a nested dictionary into a list. [GFGTABS] Python a = { "a": {"x": 1, "y": 2}, "b": {"x
3 min read
Inverse Dictionary Values List - Python
We are given a dictionary and the task is to create a new dictionary where each element of the value lists becomes a key and the original keys are grouped as lists of values for these new keys.For example: dict = {1: [2, 3], 2: [3], 3: [1]} then output will be {2: [1], 3: [1, 2], 1: [3]} Using defau
2 min read
Appending into a List in Python Dictionary
Python dictionaries are powerful data structures that allow us to store and retrieve data using key-value pairs. Appending an item to a list within a dictionary involves accessing the list by its corresponding key and then using the append() method to add the new item to the list in Python. Example:
5 min read
Python - Convert List to List of dictionaries
We are given a lists with key and value pair we need to convert the lists to List of dictionaries. For example we are given two list a=["name", "age", "city"] and b=[["Geeks", 25, "New York"], ["Geeks", 30, "Los Angeles"], ["Geeks", 22, "Chicago"]] we need to convert these keys and values list into
4 min read