Convert List to Key - Value List by Prefix Grouping - Python
Last Updated :
21 Jan, 2025
Given a list, we are required to convert it into a dictionary of consecutive key-value pairs where the key is a string (starting with a prefix) and the values are grouped by that prefix until the next key with the same prefix is encountered.
For example: We have a list ["GFG-1", 4, 6, "GFG-2", 3, "GFG-3", 9, 2]
and s = "GF" then the output will be
{'GFG-1': [4, 6], 'GFG-2': [3], 'GFG-3': [9, 2]}
Using groupby()
and startswith()
In this method we use groupby()
from itertools
along with a lambda
function that checks if the element starts with a given prefix, groupby() groups the elements based on the prefix and converts the list into key-value pairs where the key is the prefix and the values are the corresponding elements.
Python
from itertools import groupby
li = ["GFG-1", 4, 6, 7, 10, "GFG-2", 2, 3, "GFG-3", 9, 2, 4, 6]
s = "GFG"
res = {}
# Extracting result from grouped by prefix
for key, val in groupby(li, lambda ele: str(ele).startswith(s)):
# checking for existing key
if key:
k = next(val)
else:
res[k] = list(val)
print("dictionary : " + str(res))
Outputdictionary : {'GFG-1': [4, 6, 7, 10], 'GFG-2': [2, 3], 'GFG-3': [9, 2, 4, 6]}
Explanation: groupby(li, lambda ele: str(ele).startswith(s))
divides the list into groups based on whether elements start with "GFG" or not. The key
will be True
for "GFG" prefixed elements and False
for numbers while val
contains those grouped elements.
Using defaultdict
In this method, we use a defaultdict with list as the default value type to group elements in the list by their prefix. Each time an element starts with the prefix, it is treated as a key. Subsequent non-key elements are added to the list under the last valid key.
Python
from collections import defaultdict
li = ["GFG-1", 4, 6, 7, 10, "GFG-2", 2, 3, "GFG-3", 9, 2, 4, 6]
s = "GFG"
res = defaultdict(list)
# iterating through the list and appending the values to the dictionary
for i in li:
if str(i).startswith(s):
key = i
else:
res[key].append(i)
print("dictionary", dict(res))
Outputdictionary {'GFG-1': [4, 6, 7, 10], 'GFG-2': [2, 3], 'GFG-3': [9, 2, 4, 6]}
Using Loop and Dictionary
In this method we will use a for
loop to iterate through the list and for each element we check if it is a string using the isinstance()
method and whether it starts with the given prefix using the startswith()
method. If both conditions are true, we treat the current element as a key and add it to the dictionary with an empty list as its value but if the element is not a string or does not start with the prefix we append it to the list associated with the current key.
Python
li = ["GFG-1", 4, 6, 7, 10, "GFG-2", 2, 3, "GFG-3", 9, 2, 4, 6]
s = "GFG"
res = {}
key = ""
for i in li:
if isinstance(i, str) and i.startswith(s):
key = i
res[key] = []
else:
res[key].append(i)
print("dictionary:", res)
Outputdictionary: {'GFG-1': [4, 6, 7, 10], 'GFG-2': [2, 3], 'GFG-3': [9, 2, 4, 6]}
Using List Comprehension and Slicing
In this method we try to identify indices of prefix elements using a list comprehension and then use dictionary comprehension to slice the list dynamically, grouping elements between indices for intermediate keys and the rest for the last key.
Python
li = ["GFG-1", 4, 6, 7, 10, "GFG-2", 2, 3, "GFG-3", 9, 2, 4, 6]
s = "GFG"
# Get indices of prefix occurrences
indices = [i for i, x in enumerate(li) if str(x).startswith(s)]
# Construct dictionary using slicing
res = {li[indices[i]]: li[indices[i]+1:indices[i+1]] if i < len(indices)-1 else li[indices[i]+1:] for i in range(len(indices))}
print("dictionary:", res)
Outputdictionary: {'GFG-1': [4, 6, 7, 10], 'GFG-2': [2, 3], 'GFG-3': [9, 2, 4, 6]}
Explanation:
indices = [i for i, x in enumerate(li) if str(x).startswith(s)] is used to collect indices where elements start with the prefix s ("GFG").
- res = {li[indices[i]]: li[indices[i]+1:indices[i+1]] if i < len(indices)-1 else li[indices[i]+1:] for i in range(len(indices))} is used to build a dictionary where keys are the prefix elements and values are slices of the list between consecutive prefixes or from the last prefix to the end.
Similar Reads
Python - Convert Key-Value list Dictionary to List of Lists We are given a key value list dictionary we need to convert it list of lists. For example we are given a dictionary a = {'name': 'Geeks', 'age': 8, 'city': 'Noida'} we need to convert this into list of lists so the output should be [['name', 'Geeks'], ['age', 25], ['city', 'Geeks']]. Using List Comp
2 min read
Python - Convert String List to Key-Value List dictionary Given a string, convert it to key-value list dictionary, with key as 1st word and rest words as value list. Input : test_list = ["gfg is best for geeks", "CS is best subject"] Output : {'gfg': ['is', 'best', 'for', 'geeks'], 'CS': ['is', 'best', 'subject']} Explanation : 1st elements are paired with
8 min read
Python | Grouping dictionary keys by value While performing computations over dictionary, we can come across a problem in which we might have to perform the task of grouping keys according to value, i.e create a list of keys, it is value of. This can other in cases of organising data in case of machine learning. Let's discuss certain way in
4 min read
Convert List of Tuples to Dictionary Value Lists - Python The task is to convert a list of tuples into a dictionary where the first element of each tuple serves as the key and the second element becomes the value. If a key appears multiple times in the list, its values should be grouped together in a list.For example, given the list li = [(1, 'gfg'), (1, '
4 min read
Python - Group keys to values list Sometimes, while working with Python dictionaries, we can have problem in which we need to find all possible values of all keys in a dictionary. This utility is quite common and can occur in many domains including day-day programming and school programming. Lets discuss certain way in which this tas
5 min read
Convert Each List Element to Key-Value Pair - Python We are given a list we need to convert it into the key- value pair. For example we are given a list li = ['apple', 'banana', 'orange'] we need to convert it to key value pair so that the output should be like {1: 'apple', 2: 'banana', 3: 'orange'}. We can achieve this by using multiple methods like
3 min read
Convert List of Tuples To Multiple Lists in Python When working with data in Python, it's common to encounter situations where we need to convert a list of tuples into separate lists. For example, if we have a list of tuples where each tuple represents a pair of related data points, we may want to split this into individual lists for easier processi
3 min read
Python | Grouping list values into dictionary Sometimes, while working with data, we can be encountered a situation in which we have a list of lists and we need to group its 2nd index with the common initial element in lists. Let's discuss ways in which this problem can be solved. Method 1: Using defaultdict() + loop + dict() The defaultdict ca
7 min read
Python | Convert list of tuples into list In Python we often need to convert a list of tuples into a flat list, especially when we work with datasets or nested structures. In this article, we will explore various methods to Convert a list of tuples into a list. Using itertools.chain() itertools.chain() is the most efficient way to flatten a
3 min read
Python - Convert list of dictionaries to Dictionary Value list We are given a list of dictionaries we need to convert it to dictionary. For example, given a list of dictionaries: d = [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}, {'a': 5, 'b': 6}], the output should be: {'a': [1, 3, 5], 'b': [2, 4, 6]}.Using Dictionary ComprehensionUsing dictionary comprehension, we can
3 min read