Open In App

Python program that renders a dictionary from two list with K values

Improve
Improve
Like Article
Like
Save
Share
Report

Given two list, one will be used to provide keys to dictionary and the other for values. The following program takes K values from second list and assigns it to each key, creating a dictionary of the following kind:

Input : test_list = [“gfg”, “best”], val_list = [1, 4, 5, 6, 7, 8, 8, 5], K = 4 
Output : {‘gfg’: [1, 4, 5, 6], ‘best’: [7, 8, 8, 5]} 
Explanation : Equal elements paired to each key.

Input : test_list = [“gfg”], val_list = [1, 4, 5, 6], K = 4 
Output : {‘gfg’: [1, 4, 5, 6]} 
Explanation : All elements assigned to only key. 

Method: Using loop and slicing 

Python3




from collections import defaultdict
 
# initializing list
test_list = ["gfg", "is", "best", "good"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing values list
val_list = [1, 4, 5, 6, 7, 8, 8, 5, 4]
 
# initializing K
K = 2
 
# work list
val_list = val_list[:(len(test_list) * K)]
 
# gets required dictionary list
res = defaultdict(list)
key_cnt = 0
for idx in range(0, len(val_list)):
     
    # append values to required keys   
    res[test_list[key_cnt]].append(val_list[idx])
     
    # increment keys when K
    if (idx + 1) % K == 0:
        key_cnt += 1
 
# printing result
print("The constructed dictionary : " + str(dict(res)))


Output

The original list is : ['gfg', 'is', 'best', 'good']
The constructed dictionary : {'gfg': [1, 4], 'is': [5, 6], 'best': [7, 8], 'good': [8, 5]}

Method #2: Using list comprehension and zip

Approach:

we use a list comprehension and the built-in Python function zip to group the elements in val_list into lists of length K, and then assigns the resulting lists as values for the keys in the dictionary

Algorithm:

1. Initialize an empty dictionary.
2. Calculate the number of slices required based on the length of the val_list and K value.
3. Use list comprehension and zip to group the val_list elements into lists of length K.
4. Assign the resulting lists as values for the keys in the dictionary.
5. Return the resulting dictionary.

Python3




def render_dict(test_list, val_list, K):
    result_dict = {}
    slices = len(val_list) // K + (1 if len(val_list) % K != 0 else 0)
    val_slices = [val_list[i*K:i*K+K] if i*K+K < len(val_list) else val_list[i*K:] for i in range(slices)]
    result_dict = {k: v for k, v in zip(test_list, val_slices)}
    return result_dict
test_list = ["gfg", "is", "best", "good"]
val_list = [1, 4, 5, 6, 7, 8, 8, 5, 4]
K=2
print(render_dict(test_list, val_list, K))


Output

{'gfg': [1, 4], 'is': [5, 6], 'best': [7, 8], 'good': [8, 5]}

Time complexity: O(n), where n is the length of val_list. The list comprehension and zip operations iterate over val_list once.
Space complexity: O(m), where m is the length of test_list. The resulting dictionary has one key-value pair for each element in test_list. Additionally, the val_slices list has length n/K or n/K + 1, depending on the remainder of n/K, which is also bounded by O(m).

METHOD 3:Using itertools and zip_longest functions

APPROACH:

This approach uses the zip_longest function from the itertools module to iterate over the three lists (keys, values1, values2) in parallel, filling missing values with None.

ALGORITHM:

1. Import the zip_longest function from the itertools module.
2.Create the keys, values1, and values2 lists.
3.Create an empty dictionary result_dict.
4.Use a for loop to iterate over the three lists in parallel using the zip_longest function, filling missing values with None.
5.For each iteration of the loop, use the setdefault method to add the key to the dictionary if it’s not already present, and initialize its value as an empty list. Append v1 and v2 to the corresponding key’s list.
6.Print the resulting dictionary result_dict.

Python3




from itertools import zip_longest
 
keys = ['gfg', 'is', 'best', 'good']
values1 = [1, 5, 7, 8]
values2 = [4, 6, 8, 5]
 
result_dict = {}
for k, v1, v2 in zip_longest(keys, values1, values2, fillvalue=None):
    result_dict.setdefault(k, []).append(v1)
    result_dict.setdefault(k, []).append(v2)
 
print(result_dict)


Output

{'gfg': [1, 4], 'is': [5, 6], 'best': [7, 8], 'good': [8, 5]}

Time complexity: O(n)
Space complexity: O(n)

Approach#4: Using lambda

The lambda function takes three arguments – test_list, val_list, and k. A dictionary comprehension is used to create a dictionary with test_list elements as keys and a subset of val_list as values. The subset of val_list is obtained using slicing based on the value of k and the length of the val_list and test_list.

Algorithm

1. Define a lambda function create_dict that takes three arguments – test_list, val_list, and k.
2. Inside the lambda function, create a dictionary using a dictionary comprehension that iterates over each element in test_list.
3. For each element in test_list, slice the val_list based on k and the length of the val_list and test_list to obtain a subset of val_list.
4. Assign the subset of val_list as the value for the corresponding key in the dictionary.
5. Return the dictionary.
6. Call the lambda function with the given inputs and print the result.

Python3




create_dict = lambda test_list, val_list, k: {test_list[i]: val_list[i*min(k,len(val_list)//len(test_list)):(i+1)*min(k,len(val_list)//len(test_list))] for i in range(len(test_list))}
 
test_list = ["gfg", "best"]
val_list = [1, 4, 5, 6, 7, 8, 8, 5]
k = 4
 
result_dict = create_dict(test_list, val_list, k)
print(result_dict)


Output

{'gfg': [1, 4, 5, 6], 'best': [7, 8, 8, 5]}

Time Complexity: O(n), where n is the length of the val_list.
Space Complexity: O(m), where m is the length of the test_list.



Last Updated : 18 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads