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
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.
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.
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.
Like this, Python's dict()
function is perfectly designed for converting a list
of tuple
s, 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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With