字典在While循环中被覆盖

时间:2019-10-08 20:09:58

标签: python python-3.x dictionary

def get_list_expenses():
  expense_list = {}
  print('Please type the name of the expense followed by the price of the expense')
  while True:
    name = input('Name of expense: ')
    price = int(input('Price of expense: '))
    expense_list.update({
        'name': name,
        'price': price,
    })
    cont = input('Want to add another? [y/n] ').lower()
    if cont == 'n':
        break
 print(type(expense_list))
 print(expense_list)
 return expense_list

Input ==========================
Please type the name of the expense followed by the price of the expense
Name of expense: Food
Price of expense: 100
Want to add another? [y/n] y
Name of expense: Car Insurance
Price of expense: 200
Want to add another? [y/n] n

Output =========================
<class 'dict'>
{'name': 'car', 'price': 200}

我是python的新手,想尝试做一个预算应用程序来节省我手动输入信息到excel的时间。我的想法是创建一个循环,以费用的名称和每月的价格为准。我想将其放入dictionary中,以便在需要时可以.get信息。但是,我的字典不断被覆盖。我尝试了一些可以在网上找到的不同解决方案,但没有任何效果。预先感谢。

4 个答案:

答案 0 :(得分:0)

在字典上使用update方法,基本上是在每次迭代时都从头开始重写字典,因此,您在最后看到一个值(最后一个)。

我建议创建一个空列表,然后在每次迭代时附加一个新的值字典:

def get_list_expenses():
  expense_list = []
  print('Please type the name of the expense followed by the price of the expense')
  while True:
    name = input('Name of expense: ')
    price = int(input('Price of expense: '))
    expense_list.append({
        'name': name,
        'price': price,
    })
    cont = input('Want to add another? [y/n] ').lower()
    if cont == 'n':
        break
 print(type(expense_list))
 print(expense_list)
 return expense_list

答案 1 :(得分:0)

BROWSER= safari npm start

应该是:

expense_list.update({
    'name': name,
    'price': price,
})

答案 2 :(得分:0)

字典是一个键值对。在您的情况下,键将是“费用名称”,值将是价格。创建方式中,词典中有2个键。第一个键是“名称”,第二个键是“价格”。

您可以简单地做到:

expense_list[name] = price

如果名称存在,它将更新,否则将添加。

答案 3 :(得分:0)

expense_list设为实际列表:

expense_list = []

然后append

expense_list.append({
    'name': name,
    'price': price,
    })