To split a string into a dictionary using Python, the easiest way is to use the Python split() function and dictionary comprehension. With this method, you will get a dictionary where the keys are numbers and the values are the words of the string.

string = "this is a string with some words"

d = { idx: ele for idx, ele in enumerate(string.split())}

print(d)

#Output:
{0: 'this', 1: 'is', 2: 'a', 3: 'string', 4: 'with', 5: 'some', 6: 'words'}

You can also use a loop explicitly to create a dictionary from a string.

string = "this is a string with some words"

d = dict()

for idx, ele in enumerate(string.split()):
    d[idx] = ele

print(d)

#Output:
{0: 'this', 1: 'is', 2: 'a', 3: 'string', 4: 'with', 5: 'some', 6: 'words'}

When working with strings and text in Python, the ability to manipulate and create new objects from strings can be useful.

One such situation is if you want to take a string and create a dictionary with the words from the string. You can split a string into a dictionary easily with the Python split() function and dictionary comprehension.

Given a string, you can use split() to split a string by a delimiter into a list.

Then, you can use enumerate() to get the index and values of the list of words and use dictionary comprehension to create a new dictionary.

Below is an example of how you can split a string into a dictionary using Python.

string = "this is a string with some words"

d = { idx: ele for idx, ele in enumerate(string.split())}

print(d)

#Output:
{0: 'this', 1: 'is', 2: 'a', 3: 'string', 4: 'with', 5: 'some', 6: 'words'}

How to Split String into Dictionary of Words Using Python

Above is a one line solution to the question of how to split a string into a dictionary of words in your Python code.

You can be more explicit and use a for loop if there are any other manipulations or additive things you need to add to your dictionary.

Below is another example of how to split a string into a dictionary.

Notice we are still using split() and enumerate(). The difference now is that we are building the dictionary from scratch.

string = "this is a string with some words"

d = dict()

for idx, ele in enumerate(string.split()):
    d[idx] = ele

print(d)

#Output:
{0: 'this', 1: 'is', 2: 'a', 3: 'string', 4: 'with', 5: 'some', 6: 'words'}

Hopefully this article has been useful for you to learn how to split a string into a dictionary using Python.

Categorized in:

Python,

Last Update: March 12, 2024