How to make a python dictionary from a line

Transform strings into dictionaries in Python with an easy-to-follow example: create a dict from a string, access items & modify values.

Creating a Python Dictionary From a Line

Creating a Python dictionary from a line of text is a fairly straightforward process. Python's built-in methods make it easy to create a dictionary from a line of text, and it can be done in just a few steps.

To create a Python dictionary from a line of text, start by splitting the line into separate words. This can be done using the split() method, which takes a string and splits it into a list of words. For example, if the line of text is "apple orange banana", the following code will split it into a list:


line = "apple orange banana"
words = line.split()
print(words)

# Output: ['apple', 'orange', 'banana']

Once the line has been split into a list of words, it is easy to create a dictionary. The dict() method takes a list of tuples and creates a dictionary from them. Each tuple consists of a key and a value, and the keys are used as the keys in the dictionary. For example, the following code will create a dictionary from the list of words created above:


words_dict = dict(zip(words, range(len(words))))
print(words_dict)

# Output: {'apple': 0, 'orange': 1, 'banana': 2}

And that's all there is to it! Python makes it easy to create a dictionary from a line of text using its built-in methods. With just a few lines of code, you can quickly turn a line of text into a useful dictionary.

Answers (0)