How to iterate through dict in random order in Python?

前端 未结 5 1659
南笙
南笙 2020-12-11 00:31

How can I iterate through all items of a dictionary in a random order? I mean something random.shuffle, but for a dictionary.

5条回答
  •  庸人自扰
    2020-12-11 01:14

    import random
    
    def main():
    
        CORRECT = 0
    
        capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau',
            'Arizona': 'Phoenix', 'Arkansas': 'Little Rock'} #etc... you get the idea of a dictionary
    
        allstates = list(capitals.keys()) #creates a variable name and list of the dictionary items
        random.shuffle(allstates) #shuffles the variable
    
        for a in allstates: #searches the variable name for parameter
            studentinput = input('What is the capital of '+a+'? ')
            if studentinput.upper() == capitals[a].upper():
                CORRECT += 1
    main()
    

提交回复
热议问题