1

I have a dictionary that has some values like dict['0']= ['1', '.....' , '2' , '5'] And i want to make the '2' and '5' (basically what comes after the string with the dots into integers. i tried with dict[i[0]] = int(i[1:]) but the int method doesnt work on lists.

daskou
  • 11
  • 1

2 Answers2

1

You could loop through the list and cast every element to an int:

[int(i) for i in dictionary['0']]
user1717828
  • 6,812
  • 6
  • 31
  • 52
0

You can use list comprehension and explicitly check for a 2 or 5:

d['0'] = [int(val) if val in ('2', '5') else val for val in d['0']]

Here is an example:

In [12]: d
Out[12]: {'0': ['0', '1', '2', '3', '4', '5']}

In [13]: d['0'] = [int(val) if val in ('2', '5') else val for val in d['0']]

In [14]: d
Out[14]: {'0': ['0', '1', 2, '3', '4', 5]}

You can also use enumerate to check if the index is past a certain index you want to convert.

For example, convert the values after index 1 to an int:

In [17]: d
Out[17]: {'0': ['0', '1', '2', '3', '4', '5']}

In [18]: d['0'] = [int(val) if i > 1 else val for i, val in enumerate(d['0'])]

In [19]: d
Out[19]: {'0': ['0', '1', 2, 3, 4, 5]}
Chrispresso
  • 3,485
  • 13
  • 26