Convert Dictionary to String List in Python
The task of converting a dictionary to a string list in Python involves transforming the key-value pairs of the dictionary into a formatted string and storing those strings in a list.
For example, consider a dictionary d = {1: 'Mercedes', 2: 'Audi', 3: 'Porsche', 4: 'Lambo'}. Converting this to a string list would result in a list like ['1: Mercedes', '2: Audi', '3: Porsche', '4: Lambo'].
Using list comprehension
List comprehension is a efficient way to convert a dictionary into a list of formatted strings. It combines iteration and string formatting in a single line, making it a highly Pythonic solution. This method is simple to read and write, making it ideal for quick transformations.
d = {1: 'Mercedes', 2: 'Audi', 3: 'Porsche', 4: 'Lambo'}
res = [f"{key}: {val}" for key, val in d.items()]
print(res)
d = {1: 'Mercedes', 2: 'Audi', 3: 'Porsche', 4: 'Lambo'}
res = [f"{key}: {val}" for key, val in d.items()]
print(res)
Output
['1: Mercedes', '2: Audi', '3: Porsche', '4: Lambo']
Explanation:
- d.items() retrieves all key-value pairs as tuples e.g., (1, 'Mercedes') .
- List comprehension iterates through key-value pairs, formatting each as f"{k}: {v}".
Using map()
map() applies a given transformation function to each element of an iterable. When working with dictionaries, it allows us to process each key-value pair systematically, converting them into formatted strings. This method is particularly useful if we prefer a functional programming approach over explicit loops .
d = {1: 'Mercedes', 2: 'Audi', 3: 'Porsche', 4: 'Lambo'}
res = list(map(lambda kv: f"{kv[0]}: {kv[1]}", d.items()))
print(res)
d = {1: 'Mercedes', 2: 'Audi', 3: 'Porsche', 4: 'Lambo'}
res = list(map(lambda kv: f"{kv[0]}: {kv[1]}", d.items()))
print(res)
Output
['1: Mercedes', '2: Audi', '3: Porsche', '4: Lambo']
Explanation:
- d.items() retrieves key-value pairs as tuples e.g., (1, 'Mercedes').
- lambda kv: f"{kv[0]}: {kv[1]}" formats each tuple as a string e.g., (1, 'Mercedes') → "1: Mercedes" .
- map() applies the lambda function to each tuple in d.items().
- list() converts the result from map() into a list .
Using join()
join()
combine multiple strings into a single string. When paired with a generator expression, it becomes an elegant solution for transforming and formatting dictionary data into a list of strings. This approach is particularly efficient for tasks where we also need the data as a single string at some point.
d = {1: 'Mercedes', 2: 'Audi', 3: 'Porsche', 4: 'Lambo'}
res= ", ".join(f"{k}: {v}" for k, v in d.items()).split(", ")
print(res)
d = {1: 'Mercedes', 2: 'Audi', 3: 'Porsche', 4: 'Lambo'}
res= ", ".join(f"{k}: {v}" for k, v in d.items()).split(", ")
print(res)
Output
['1: Mercedes', '2: Audi', '3: Porsche', '4: Lambo']
Explanation:
- f"{key}: {val}" for key, val in d.items() formats each tuple as a string e.g., (1, 'Mercedes') → "1: Mercedes".
- ", ".join() combines the formatted strings into a single string, separated by commas .
- .split(", ") splits the combined string back into a list using the comma and space separator.
Using loop
Loop is the traditional approach to convert a dictionary into a string list. It is ideal when we need more control over the transformation process or when additional operations need to be performed alongside formatting .
d = {1: 'Mercedes', 2: 'Audi', 3: 'Porsche', 4: 'Lambo'}
res = [] # initializes empty list
for key, val in d.items(): # iterates over key-value pairs in `d`
res.append(f"{key}: {val}")
print(res)
d = {1: 'Mercedes', 2: 'Audi', 3: 'Porsche', 4: 'Lambo'}
res = [] # initializes empty list
for key, val in d.items(): # iterates over key-value pairs in `d`
res.append(f"{key}: {val}")
print(res)
Output
['1: Mercedes', '2: Audi', '3: Porsche', '4: Lambo']
Explanation:
- d.items() retrieves key-value pairs as tuples .
- res.append(f"{key}: {val}") formats each tuple as a string and appends it to the list res.