Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (45.3k points)

I have a list of about 50 strings with an integer representing how frequently they occur in a text document. I have already formatted it like shown below, and am trying to create a dictionary of this information, with the first word being the value and the key is the number beside it.

string = [('limited', 1), ('all', 16), ('concept', 1), ('secondly', 1)]

The code I have so far:

my_dict = {}

for pairs in string:

    for int in pairs:

       my_dict[pairs] = int

1 Answer

0 votes
by (16.8k points)

Like this, Python's dict() function is perfectly designed for converting a list of tuples, which is what you have:

>>> string = [('limited', 1), ('all', 16), ('concept', 1), ('secondly', 1)]

>>> my_dict = dict(string)

>>> my_dict

{'all': 16, 'secondly': 1, 'concept': 1, 'limited': 1}

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
4 answers

Browse Categories