-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
  • 52,115
  • 13
  • 74
  • 94

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
  • 147,904
  • 31
  • 244
  • 302
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
  • 5,652
  • 2
  • 19
  • 36