Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python convert pairs list to dictionary

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 
like image 653
user2968861 Avatar asked Mar 24 '14 16:03

user2968861


People also ask

How do I convert a list to a dictionary in Python?

Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.

How do you convert a list to a key value pair in Python?

By using enumerate() , we can convert a list into a dictionary with index as key and list item as the value. enumerate() will return an enumerate object. We can convert to dict using the dict() constructor.

How do you obtain a list of tuples of key value pairs in a dictionary dict?

One of the built-in methods for dictionaries is the . items() methods, which returns a tuple of tuples of the key value pairs found inside the dictionary. We can use this method and pass it into the list() function, in order to generate a list of tuples that contain the key value pairs from our dictionary.


1 Answers

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} 
like image 116
anon582847382 Avatar answered Sep 24 '22 15:09

anon582847382