从字典中打印python

时间:2017-11-20 15:55:26

标签: python dictionary

我试图编写能够收集参加活动的人数的代码。根据输入的人数,我会多次询问a)个人姓名,b)他们捐赠的玩具数量。我希望将信息输入到字典中,我将传递给另一个函数。第二个功能将选择捐赠超过20个玩具的个人,并打印他们的名字和捐赠的玩具数量为"等级1"然后其他人为" 2级"。

我已经检查过以确保数据正确地从一个功能传递到另一个功能。我在没有[]的情况下打印捐赠金额时遇到问题。此外,它会在每个条目上方保持打印级别,而不是列出级别下的条目。换句话说,我试图获得:

  

等级1   Selena Gomez 50
  Beyonce 40

     

2级   Will Smith 5

我做错了什么?

这是我的代码:

def data():
    people = int(input("How many individuals are attending? "))
    attendees = {}
    for i in range(people):
        name = str(input('Please enter name: '))
        amount = int(input('Number of toys donated:'))
        attendees[name]= [amount]

    return attendees




def print_data():
    attendees = data()

    for i in attendees:
        if attendees[i][0] > 20:
            print('Level 1')
            print(i, attendees[i])

        else:    
            print('Level 2')
            print(i, attendees[i])

print_data()

这是我的输出:

  

有多少人参加? 3

     

请输入姓名:Will Smith

     

捐赠的玩具数量:5

     

请输入姓名:Selena Gomez

     

捐赠的玩具数量:50

     

请输入姓名:Beyonce

     

捐赠的玩具数量:40

     

2级   威尔史密斯[5]

     

等级1   Selena Gomez [50]

     

等级1   碧昂丝[40]

3 个答案:

答案 0 :(得分:1)

你犯了两个错误,你把输入作为列表作为每个字典元素的值,你必须运行两个不同的循环来找到大于20的所有值,另一个打印所有小于20的值

def data():
    people = int(input("How many individuals are attending? "))
    attendees1 = {}
    attendees2 = {}
    for i in range(people):
        name = str(input('Please enter name: '))
        amount = int(input('Number of toys donated:'))
        #amount should be just a variable not list
        if amount > 20:
            attendees1[name]= amount
        else:
            attendees2[name] = amount

    return attendees1, attendees2




def print_data():
    attendees1, attendees2 = data()


    if len(attendees1) > 0:
        print('Level 1')
        for i in attendees1:
            print(i, attendees1[i])

    if len(attendees2) > 0:
        print('Level 2')
        for i in attendees2:
            print(i, attendees2[i])

print_data()

答案 1 :(得分:0)

应编辑这两行:

attendees[name]= [amount]
#into
attendees[name]= amount
#and
if attendees[i][0] > 20:
#into
if attendees[i] > 20:

答案 2 :(得分:0)

这样的事情对你有用吗?

def data():
    people = int(input("How many individuals are attending? "))
    attendees = {}
    for i in range(people):
        name = str(input('Please enter name: '))
        amount = int(input('Number of toys donated:'))
        attendees[name]= amount
    return attendees


def print_data(attendees):
    level_one = []
    level_two = []
    for name, count in attendees.items():
        if count >= 20:
            level_one.append((name, count))
        else:
            level_two.append((name, count))

    print('Level 1')
    for name, count in level_one:
        print(name, count)

    print('\nlevel 2')
    for name, count in level_two:
        print(name, count)


attendees = data()
print_data(attendees)