if __name__ == '__main__':
for _ in range(int(input())):
name = input()
score = float(input())
a=[]
a.append([name][score])
print(a)
This is error occurred when I insert values
Traceback (most recent call last):
File "C:/Users/Administrator/Desktop/Nested Lists.py", line 6, in <module>
a.append([name][score])
TypeError: list indices must be integers or slices, not float
The syntax to make a list containing name and score is [name, score]. [name][score] means to create a list containing just [name], and then use score as an index into that list; this doesn't work because score is a float, and list indexes have to be int.
You also need to initialize the outer list only once. Putting a=[] inside the loop overwrites the items that you appended on previous iterations.
a=[]
for _ in range(int(input())):
name = input()
score = float(input())
a.append([name, score])
print(a)
Use a dictionary instead of a list (a list will work, but for what you are doing a hashmap is better suited):
if __name__ == '__main__':
scores = dict()
for _ in range(int(input())):
name = input()
score = float(input())
scores[name] = score
print(scores)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With