How to Split a String into a Dictionary in Python?

Estimated read time 2 min read

To split a string into a dictionary in Python, you can use the split() function to separate the string into key-value pairs, and the dict() function to create a dictionary from the pairs. Here’s an example:

string = "name=John&age=30&city=New+York"
items = string.split("&")
dictionary = {}
for item in items:
    key, value = item.split("=")
    dictionary[key] = value.replace("+", " ")

print(dictionary)

In this example, we start with a string that contains key-value pairs separated by an ampersand (&) character, and each key-value pair separated by an equals (=) character.

We use the split() function to split the string into a list of individual key-value pairs.

We create an empty dictionary called dictionary to store the key-value pairs.

We use a for loop to iterate over each item in the list of key-value pairs. We use the split() function again to split each item into its key and value components. We then add each key-value pair to the dictionary.

We replace any plus signs (+) in the value strings with spaces using the replace() function to handle URL encoding.

We print the resulting dictionary to the console.

The output of this example would be:

{'name': 'John', 'age': '30', 'city': 'New York'}

Note that this is just a basic example of how to split a string into a dictionary in Python. You can customize the code to suit your specific needs, such as handling different separator characters or working with more complex key-value pairs. Additionally, keep in mind that this method assumes that the input string is well-formed and does not contain any unexpected or malformed key-value pairs.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply