1

i just want make a list to display students scores and different course have different scores ,the scores comes from.random randint(70,100), like this:

[{'C++':70,'Math':80,'Python':90},
{'C++':87,'Math':82,'Python':91},...]

import random
def makedict(spam):
    a=[]
    for j in range(20):             
        for i in spam:
        a[j].setdefault(i,random.randint(70,90))
    return a
if __name__=="__main__":
    cou=['C++','Math',Python]
    res=makedict(cou)

IndexError: list index out of range how i change the code

1
  • use a.append instead of indexing Commented Oct 21, 2016 at 6:11

3 Answers 3

2

use dictionary comprehension

import random
def makedict(subjects):
    return {s: random.randint(70,100) for s in subjects}

if __name__=="__main__":
    cou=['C++','Math','Python']
    res=makedict(cou)
Sign up to request clarification or add additional context in comments.

1 Comment

i want to make more than one dictionary,so your answer is also good if add a loop
0

Try this, You have to use append.

import random
def makedict(spam):
    result = []
    for _ in range(20):
        result.append({j:random.randint(70,90) for j in spam})
    return result

if __name__=="__main__":
    cou=['C++','Math', 'Python']
    res=makedict(cou)

1 Comment

i also use append,but i don't know {j:random.randint(70,90) for j in spam},so it's good for me to learn
0

Your indentation for the second for..loop is wrong. Fix it and it will work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.