-1
dic={}
l=[]
for i in range(0,2):
    c=input("Enter your name").strip()

    for i in range(0,3):
        d=int(input("Enter Your marks: "))
        l.append(d)
    dic[c]=l



print(dic)
print(l)

Output:

{'alex': [36, 54, 78, 57, 78, 94], 'harry': [36, 54, 78, 57, 78, 94]}

Expected Output:

{'alex': [36, 54, 78], 'harry': [57, 78, 94]}

Where I am doing wrong?

khelwood
  • 55,782
  • 14
  • 81
  • 108

2 Answers2

0

You have a couple of options. Either redefine l as an empty list within your outer for loop, so that the same list is not appended to throughout. Or use collections.defaultdict to append to a default list value. Here's an example of the second option:

from collections import defaultdict

dic = defaultdict(list)
for i in range(2):
    c = input("Enter your name").strip()
    for i in range(3):
        dic[c].append(int(input("Enter Your marks: ")))

Using a defaultdict is more efficient and arguably more readable.

jpp
  • 159,742
  • 34
  • 281
  • 339
0

Lists in python are mutable objects, which mean that the l variable always points to the same list object. You could easily fix that by doing:

dic={}
for i in range(0,2):
    l=[]
    c=input("Enter your name").strip()

    #(...) 

That way, a new list object is instantiated at each iteration.

NB: you could simplify your code by using list comprehension:

dic={}
for i in range(2):
    c = input("Enter your name").strip()
    l = [int(input("Enter Your marks: ")) for _ in range(3)]     
    dic[c]=l
olinox14
  • 6,177
  • 2
  • 22
  • 39