Skip to main content
 首页 » 编程设计

python从字典打印

2025年01月19日13freeliver54

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

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

Level 1
Selena Gomez 50
Beyonce 40

Level 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() 

这是我的输出:

How many individuals are attending? 3

Please enter name: Will Smith

Number of toys donated:5

Please enter name: Selena Gomez

Number of toys donated:50

Please enter name: Beyonce

Number of toys donated:40

Level 2
Will Smith [5]

Level 1
Selena Gomez [50]

Level 1
Beyonce [40]

请您参考如下方法:

你犯了两个错误,你将输入作为列表作为每个字典元素的值,你必须运行两个不同的循环来查找所有大于 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()