Reputation: 797
I scrape down stats that get put in a list that I later want to convert to a dictionary. The list looks like this:
my_list = [('Appearances ', ' 32'),('Clean sheets ', ' 6'), etc,etc]
How do I convert the integers in the tuple to integers?
Upvotes: 1
Views: 513
Reputation: 1492
The following code will convert the strings to integers. And, it will also create a dictionary using the list of tuples.
my_list = [
('Appearances ', ' 32'),
('Clean sheets ', ' 6')
]
d = dict()
for key, value in my_list:
d[key.strip()] = int(value.strip())
print(d)
The above solution assumes each of the tuple in the list will have two elements key
& value
. All the first elements (keys) of the tuples are unique. And, the second elements (values) are strings that can be converted into integers.
Upvotes: 1
Reputation: 11
You can use list comprehension:
new_list = [(x[0], int(x[1].strip())) for x in my_list]
Upvotes: 1
Reputation: 11063
The easy, generally-applicable method would be to convert anything numeric (strings have a test for this) into an integer. The slight trick to it is that the number string can't have spaces in it to check if it's numeric (but it can have them to convert to an integer).
So:
>>> listoftuples = [('Appearances ', ' 32'), ('Clean sheets ', ' 6')]
>>> [tuple(int(item) if item.strip().isnumeric() else item for item in group) for group in listoftuples]
>>> [('Appearances ', 32), ('Clean sheets ', 6)]
The advantage of this method is that it's not specific to your input. It works fine if the integer is first, or if the tuples are different lengths, etc.
Upvotes: 2
Reputation: 1501
my_list = map(lambda x: [x[0], int(x[1].strip())], my_list)
Given an input list my_list
of OP's specifications, return the resulting list with the second value stripped of whitespace and turned into an integer.
Upvotes: 2