Python convert pairs list to dictionary
Question:
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
Answers:
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}
Just call dict()
:
>>> string = [('limited', 1), ('all', 16), ('concept', 1), ('secondly', 1)]
>>> dict(string)
{'limited': 1, 'all': 16, 'concept': 1, 'secondly': 1}
The string
variable is a list of pairs. It means you can do something somilar to this:
string = [...]
my_dict = {}
for k, v in string:
my_dict[k] = v
Make a pair of 2 lists and convert them to dict()
list_1 = [1,2,3,4,5]
list_2 = [6,7,8,9,10]
your_dict = dict(zip(list_1, list_2))
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 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}
Just call dict()
:
>>> string = [('limited', 1), ('all', 16), ('concept', 1), ('secondly', 1)]
>>> dict(string)
{'limited': 1, 'all': 16, 'concept': 1, 'secondly': 1}
The string
variable is a list of pairs. It means you can do something somilar to this:
string = [...]
my_dict = {}
for k, v in string:
my_dict[k] = v
Make a pair of 2 lists and convert them to dict()
list_1 = [1,2,3,4,5]
list_2 = [6,7,8,9,10]
your_dict = dict(zip(list_1, list_2))