Summary: There are three different ways to split the given string into keys and values:
- Using
dict()
- Using
map()
andlambda
- Using dictionary comprehension
Minimal Example
st = "a:2,b:3,c:5,d:1" li = st.split(",") # Method 1 d = dict(s.split(':') for s in li) print(d) # Method 2 d = dict(map(lambda s: s.split(':'), li)) print(d) # Method 3 res = {sub.split(":")[0]: sub.split(":")[1] for sub in li} print(res) # Output: {'a': '2', 'b': '3', 'c': '5', 'd': '1'}
Problem Formulation
Problem: Given a string containing key-value pairs. How will you split the string to get the key-value pairs?
Example
You have to split the string given in the problem below using the delimiter “:
” in such a way that everything on the left side will become keys, and everything on the right side of the delimiter becomes the values of a dictionary.
# Input: st = "Python:Rossum,C:Ritchie,Java:Gosling,C++:Stroustrup" # Output: {'Python': 'Rossum', 'C': 'Ritchie', 'Java': 'Gosling', 'C++': 'Stroustrup'}
Now without any further ado, let’s dive into the numerous ways of solving this problem.
Method 1: Using dict()
Python’s built-in dict()
function creates and returns a new dictionary object from the comma-separated argument list of key = value mappings. For example, dict(name = 'Alice', age = 22, profession = 'programmer')
creates a dictionary with three mappings: {'name': 'Alice', 'age': 22, 'profession': 'programmer'}
. A dictionary is an unordered and mutable data structure, so it can be changed after creation.
Approach: Use the split()
function with the delimiter “,
” to split the given string into a list of substrings separated by comma. Once again, use the split()
method such that the delimiter this time is “:
” to create another list which will store the keys and values as separate elements. Use the dict()
method on this list to create a dictionary with all the keys and the corresponding values.
Code:
st = "Python:Rossum,C:Ritchie,Java:Gosling,C++:Stroustrup" li = st.split(",") # Method 1 d = dict(s.split(':') for s in li) print(d) # {'Python': 'Rossum', 'C': 'Ritchie', 'Java': 'Gosling', 'C++': 'Stroustrup'}
Related Read: Python dict() — A Simple Guide with Video
Method 2: Using map() and lambda
Prerequisites:
- The
map()
function transforms one or more iterables into a new one by applying a “transformator function” to the i-th elements of each iterable. The arguments are the transformator function object and one or more iterables. - A lambda function is an anonymous function in Python. It starts with the keyword lambda, followed by a comma-separated list of zero or more arguments, followed by the colon and the return expression. For example, lambda x, y, z: x+y+z would calculate the sum of the three argument values x+y+z.
Related Read:
(i) Python map() — Finally Mastering the Python Map Function [+Video]
(ii) Lambda Functions in Python: A Simple Introduction
Approach: Use the split()
function with the delimiter “,
” to split the given string into a list of substrings. Use the map
and feed in the split list of substrings as the second argument. The first argument should be a function and you can use a lambda function here which can be used to further split the items of the list using the delimiter “:
” You can feed the map object directly to dict()
to get the dictionary with keys and values.
Code:
st = "Python:Rossum,C:Ritchie,Java:Gosling,C++:Stroustrup" li = st.split(",") d = dict(map(lambda s: s.split(':'), li)) print(d) # {'Python': 'Rossum', 'C': 'Ritchie', 'Java': 'Gosling', 'C++': 'Stroustrup'}
Method 3: Using Dictionary Comprehension
Prerequisite: Dictionary Comprehension is a concise and memory-efficient way to create and initialize dictionaries in one line of Python code. It consists of two parts: expression and context. The expression defines how to map keys to values. The context loops over an iterable using a single-line for loop and defines which (key,value) pairs to include in the new dictionary.
Approach: Use the split()
function with the delimiter “,
” to split the given string into a list of substrings. You have to further use the split() method and the delimiter “:” on every substring and use dictionary comprehension to create a mapping from keys (the first element of the substring) to the values (the second element of the substring). The second split can be effectively performed within the expression.
Code:
st = "Python:Rossum,C:Ritchie,Java:Gosling,C++:Stroustrup" li = st.split(",") res = {sub.split(":")[0]: sub.split(":")[1] for sub in li} print(res) # {'Python': 'Rossum', 'C': 'Ritchie', 'Java': 'Gosling', 'C++': 'Stroustrup'}
Related Read: Python Dictionary Comprehension: A Powerful One-Liner Tutorial
Exercise
Here’s a different challenge for you based on what you learned above.
Challenge: You have been given a string separated by “-“. However, this string does not have key-value pairs. It only has the values. Split the string and create key-value pairs such that the keys are consecuitive integers starting from one. Thus, you will have 4 keys and 4 values (the values are the substrings in the given string).
# Given String text = 'KBDNM-R8CD9-RK366-WFM3X-C7GXK' # Expected Output: {1: 'KBDNM', 2: 'R8CD9', 3: 'RK366', 4: 'WFM3X', 5: 'C7GXK'}
💡Hint: Python | Split String into Variables
Approach: The idea here is to split the list using “-” as the delimiter and then find the length of the resultant list returned by the split function. Then use this length to create another list containing all the keys as items within it. This can be done with the help of a simple for loop. Thus, you will effectively have two lists – one that stores the split strings/values and another that stores the keys.
You can then create a dictionary out of the two lists such that the keys in this dictionary will be the items of the list containing the integers and the values in this dictionary will be the items of the list containing the split strings.
Solution:
# Given String text = 'KBDNM-R8CD9-RK366-WFM3X-C7GXK' # splitting the string using - as a separator res = text.split('-') # Naming and storing variables and values name = [] for i in range(1, len(res)+1): name.append(i) d = dict(zip(name, res)) print(d) # {1: 'KBDNM', 2: 'R8CD9', 3: 'RK366', 4: 'WFM3X', 5: 'C7GXK'}
Conclusion
Hurray! We looked at three different ways to split the string into keys and values. I hope all the solutions mentioned in this article have helped you. Please subscribe and stay tuned for more interesting articles and solutions in the future. Happy coding!
But before we move on, I’m excited to present you my new Python book Python One-Liners (Amazon Link).
If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!
The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).