简体   繁体   English

如何在py中循环循环以获取字典

[英]How can I loop a loop in py for a dictionary

So i tried defining a function in which the classroom's names would be generated as a dictionary.所以我尝试定义一个 function ,其中教室的名称将作为字典生成。 But there seems to be an error in it and i can't find out what.但它似乎有一个错误,我不知道是什么。

This is the syntax这是语法

def classroom():
    noofclass=int(input('Enter the number of classes:'))

    noofdivision=int(input('Enter the number of divisions: '))

    x={}
    for i in range(1,noofclass + 1):

        for j in range(1,noofdivision + 1):
            dict1={i:j}
            x.update(dict1)


    print(x)

classroom()

This is the output这是 output

Enter the number of classes:2
Enter the number of divisions: 2
{1: 2, 2: 2}

The division or subclasses for some reason dont take the values other than the value for 'noofdivision'.由于某种原因,划分或子类不采用“noofdivision”值以外的值。 Can you explain why and how to fix this error.你能解释一下为什么以及如何解决这个错误。

Since a dictionary is a unique collection of keys, the second j iteration for each i overwrites the first iteration.由于字典是唯一的键集合,因此每个i的第二次j迭代会覆盖第一次迭代。

So for i=1 , key 1 is created with value 1 and then, in the second iteration of j loop, the key 1 will be overwritten by 2 .所以对于i=1 ,键1被创建为值为1 ,然后,在j循环的第二次迭代中,键1将被2覆盖。

For your use case, x should be a list of dicts .对于您的用例, x应该是dicts list Try:尝试:

def classroom():
    noofclass=int(input('Enter the number of classes:'))
    noofdivision=int(input('Enter the number of divisions: '))
    x=[]
    for i in range(1,noofclass + 1):
        for j in range(1,noofdivision + 1):
            x.append({i:j})
    print(x)

classroom() # output: [{1:1},{1:2}, {2:1}, {2:2}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM