Friday, December 27, 2024
Google search engine
HomeLanguagesPython – Assign list items to Dictionary

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 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




# Python3 code to demonstrate working of
# Assign list items to Dictionary
# Using zip() + loop
 
# initializing list
test_list = [{'Gfg': 1, 'id': 2},
             {'Gfg': 4, 'id': 4}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing key
new_key = 'best'
 
# initializing list
add_list = [12, 2]
 
# Assign list items to Dictionary
# Using zip() + loop
res = []
for sub, val in zip(test_list, add_list):
    sub[new_key] = val
    res.append(sub)
 
# printing result
print("The modified dictionary : " + str(res))
# Python3 code to demonstrate working of
# Assign list items to Dictionary
# Using zip() + loop
 
# initializing list
test_list = [{'Gfg': 1, 'id': 2},
             {'Gfg': 4, 'id': 4}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing key
new_key = 'best'
 
# initializing list
add_list = [12, 2]
 
# Assign list items to Dictionary
# Using zip() + loop
res = []
for sub, val in zip(test_list, add_list):
    sub[new_key] = val
    res.append(sub)
 
# printing result
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




# Python3 code to demonstrate working of
# Assign list items to Dictionary
# Using list comprehension + zip()
 
# initializing list
test_list = [{'Gfg': 1, 'id': 2},
             {'Gfg': 4, 'id': 4}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing key
new_key = 'best'
 
# initializing list
add_list = [12, 2]
 
# Assign list items to Dictionary
# Using list comprehension + zip()
res = [{**sub, new_key: ele} for sub, ele in zip(test_list, add_list)]
 
# printing result
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




# Python3 code to demonstrate working of
# Assign list items to Dictionary
 
# initializing list
test_list = [{'Gfg' : 1, 'id' : 2 },
            {'Gfg' : 4, 'id' : 4 }]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing key
new_key = 'best'
 
# initializing list
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])
# printing result
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




# initializing list
test_list = [{'Gfg': 1, 'id': 2},
             {'Gfg': 4, 'id': 4}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing key
new_key = 'best'
 
# initializing list
add_list = [12, 2]
 
# using filter() to construct dictionary from mapped value and key lists
res = [dict(zip([new_key], [val])) for val in add_list]
 
# using map() + update() to perform list item assign
list(map(lambda ele: ele.update(res.pop(0)), test_list))
 
# printing result
print("The modified dictionary : " + str(test_list))
 
# This code is contributed by Vinay Pinjala


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




# Python3 code to demonstrate working of
# Assign list items to Dictionary
# Using list comprehension and enumerate()
 
# initializing list
test_list = [{'Gfg': 1, 'id': 2},
             {'Gfg': 4, 'id': 4}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing key
new_key = 'best'
 
# initializing list
add_list = [12, 2]
 
# Assign list items to Dictionary
# Using list comprehension and enumerate()
res = [ { **sub, new_key: add_list[i] } for i, sub in enumerate(test_list)]
 
# printing result
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):
    # base case
    if not test_list:
        return []
     
    # recursively assign list items to dictionary
    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:])
# initializing list
test_list = [{'Gfg': 1, 'id': 2},
             {'Gfg': 4, 'id': 4}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing key
new_key = 'best'
 
# initializing list
add_list = [12, 2]
 
res = assign_list_items_to_dict(test_list, new_key, add_list)
 
# printing result
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

RELATED ARTICLES

Most Popular

Recent Comments