Python 7 Levels, L4, Unit 40, Dictionary

Powered By EmbedPress

Exercise:

stu1 = {"name":"David Smith","gender":"Male","age":13,"score":98}
stu2 = {"name":"Alice Lee","gender":"Female","age":14,"score":95}
stu3 = {"name":"Peter Pan","gender":"Female","age":13,"score":92}
stu_all = [stu1,stu2,stu3]

#Display Alice's core
print(stu_all[1].get("score"))

#View scores of all students
for i in range(len(stu_all)):
    print(stu_all[i].get("score"))

#View all information of all students
for i in range(len(stu_all)):
    print(stu_all[i].get("name"),stu_all[i].get("gender"), \
          stu_all[i].get("age"),stu_all[i].get("score"))

Homework:

print("English-Chinese Dictionary")
d = dict()#create an empty dictionary
while True:
    num = input("Please pick an operation:"\
                "\n1.Add Item\n2.Search Item\n3.Delete Item\n4.Update Item"\
                "\n5.View All Keys\n6.View All Keys and Explanations\n7.Quit\n")
    if num == "7":
        print("Abort System")
        break
    elif num == "1":
        word = input("Please input the word:")
        exp = input("Please input the explanations of the "+word+":")
        d[word] = exp

    elif num == "2":
        word = input("Please input the word you look for:")
        if word in d:
            print(d.get(word))
        else:
            print(word+" does not exist.")
    elif num == "3":
        word = input("Please input the word to be deleted:")
        if word in d:
            del(d[word])
        else:
            print(word + " does not exist.")

    elif num == "4":
        word = input("Please input the word to be updated:")
        if word in d:
            exp = input("Please update "+word+"'s explanations:")
            d[word] = exp
        else:
            print(word + " does not exist.")

    elif num == "5":
        for i in d.keys():
            print(i)
    elif num == "6":
        for i in d.items():
            for j in i:
                print(j,end = " ")
            print()#output a new line

dahan1999

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts