1

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?

0

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You bet. You can change "else item" to "else item.strip()" if you don't want the extra spaces in your other items, but I left that out since you didn't specify.
2
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.

2 Comments

When I print my_list I just get <map at 0x122ed3128>, do you perhaps know why?
This is because function map includes an iterator, not a list itself. To print it like that, you will have to first convert it (for example by list(map(...)).
1

You can use list comprehension:

    new_list = [(x[0], int(x[1].strip())) for x in my_list]

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.