Python – Convert List to key-value list by prefix grouping

Given a list, convert it to consecutive key-value lists, grouping by prefix.

Input : test_list = [“GFG-1”, 4, 6, “GFG-2”, 3, “GFG-3”, 9, 2], temp = “GF”
Output : {‘GFG-1’: [4, 6], ‘GFG-2’: [3], ‘GFG-3’: [9, 2]}
Explanation : All grouped till next prefix.

Input : test_list = [“MRK-1”, 4, 6, “MRK-2”, 3, “MRK-3”, 9, 2], temp = “MR”
Output : {‘MRK-1’: [4, 6], ‘MRK-2’: [3], ‘MRK-3’: [9, 2]}
Explanation : All grouped till next prefix, “MR”.

Method : Using groupby() + startswith() + lambda

The combination of above functions can be used to solve this problem. In this, we employ grouping of all elements by prefix using groupby() and lambda functions assists in performing segregation of prefix for grouping.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Convert List to key-value list by prefic grouping
# Using groupby() + startswith() + lambda
from itertools import groupby
  
# initializing list
test_list = ["GFG-1", 4, 6, 7, "GFG-2", 2, 3, "GFG-3", 9, 2, 4, 6]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing prefix 
temp = "GFG"
  
res = {}
# extracting result from grouped by prefix
for key, val in groupby(test_list, lambda ele: str(ele).startswith(temp)):
      
    # checking for existing key 
    if key:
        k = next(val)
    else:
        res[k] = list(val)
          
# printing result 
print("The constructed dictionary : " + str(res))

chevron_right


Output

The original list : ['GFG-1', 4, 6, 7, 'GFG-2', 2, 3, 'GFG-3', 9, 2, 4, 6]
The constructed dictionary : {'GFG-1': [4, 6, 7], 'GFG-2': [2, 3], 'GFG-3': [9, 2, 4, 6]}
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.