python:字典被覆盖

时间:2017-05-01 10:48:36

标签: python dictionary

以下代码中的字典数据的值被覆盖,尽管密钥不同,但可能是覆盖的原因。

#!/usr/local/bin/python2.7
data={}
marks = {}
subjects = ["Tamil","English","Maths","Science","Social"]

for i in range(1,3):
  print 'Enter marks for student%d'%i
  for subject in subjects:
    marks[subject] = input("Enter the " + subject + " marks: ")

  data[i]={'marks':marks}
  print data

代码输出:

Enter marks for student1
Enter the Tamil marks:  10
Enter the English marks:  20
Enter the Maths marks:  30
Enter the Science marks:  40
Enter the Social marks:  50
{1: {'marks': {'Maths': 30, 'Science': 40, 'Social': 50, 'Tamil': 10, 'English': 20}}}
Enter marks for student2
Enter the Tamil marks:  11
Enter the English marks:  12
Enter the Maths marks:  13
Enter the Science marks:  14
Enter the Social marks:  15
{1: {'marks': {'Maths': 13, 'Science': 14, 'Social': 15, 'Tamil': 11, 'English': 12}}, 2: {'marks': {'Maths': 13, 'Science': 14, 'Social': 15, 'Tamil': 11, 'English': 12}}}
{1: {'marks': {'Maths': 13, 'Science': 14, 'Social': 15, 'Tamil': 11, 'English': 12}}, 2: {'marks': {'Maths': 13, 'Science': 14, 'Social': 15, 'Tamil': 11, 'English': 12}}}

1 个答案:

答案 0 :(得分:5)

您正在重复使用相同的字典,只需在每次迭代中使用一个新字典:

#!/usr/local/bin/python2.7
data={}
subjects = ["Tamil","English","Maths","Science","Social"]

for i in range(1,3):
  print 'Enter marks for student%d'%i
  marks = {}
  for subject in subjects:
    marks[subject] = input("Enter the " + subject + " marks: ")

  data[i]={'marks':marks}
  print data