The problem is that you incorrectly initialize the lists, car = [K]
creates a list in which the elements are the characters of the string K
, that is:
>>> ["5"]
['5']
>>> ["12"]
['1', '2']
This means that if k
is "5"
, for example, your lists only have one element, so car[0]
is valid, but car[1]
is no longer valid.
You should do something like this instead:
k = int(input())
car = [None] * k
val = [None] * k
for x in range(k):
car[x], val[x] = input().split()
3
a 4
b 6
c 13
>>> car
['a', 'b', 'c']
>>> val
['4', '6', '13']
[None] * k
create a list of k
elements all None
:
>>> [None] * 5
[None, None, None, None, None]
Note: Be careful when initializing a list in this way when it comes to mutable elements since all elements are references
to the same object:
>>> l = [[]] * 5
>>> l[0].append(2)
>>> l
[[2], [2], [2], [2], [2]]
instead use a for:
>>> l = [[] for _ in range(5)]
Apparently a dictionary is the most appropriate structure to store the information you want, as long as the characters are unique:
k = int(input())
chars_count = dict((input().split() for _ in range(k)))
3
a 4
b 6
c 13
>>> chars_count
{'a': '4', 'b': '6', 'c': '13'}
>>> chars_count["c"]
"13"
>>> chars_counts["a"]
"4"
Another way, doing an entire casting of the value previously:
k = int(input())
chars_count = {}
for _ in range(k):
char, value = input().split()
chars_count[char] = int(value)
# Lo mismo usando diccionarios por compresión
# chars_count = {c: int(v) for c, v in (input().split() for _ in range(k))}
3
a 4
b 6
c 13
>>> chars_count
{'a': 4, 'b': 6, 'c': 13}