【问题标题】:Python: Add to existing dictionary value if key exists in while loop?Python:如果键存在于while循环中,则添加到现有字典值?
【发布时间】:2019-05-03 16:55:08
【问题描述】:

我现在有这个代码。

current_assets = {}
yes_list=["yes", "Yes", "y", "Y"]

while create_bs in (yes_list):

    key=str(input("Enter a specific account.\nExamples: Checking Account 
    Balance, Investment in XYZ Corp., Parking Fine Payable, Note Payable, 
    Receviable From John Smith\n"))

    value=float(input("Enter the value/historical cost of the asset or 
    liability.\n"))

    account_type=str(input("What type of account is this?\nOptions: 1) 
    Current Assets 2) Noncurrent Assets 3) Current Liabilities 4) Noncurrent 
    Liabilities\n"))

    if account_type in ("1", "Current Assets", "current assets", "CA"):
        current_assets.update({key:value})
    if key in current_assets:
        current_assets[key].append({key:value})

尝试运行时出现两个问题:

  1. 我收到一个

    AttributeError: 'float' object has no attribute 'append' 
    
  2. 该值似乎增加了两次。例如,而不是

    {Cash: 100} and {Cash: 200} becoming {Cash: (100, 200)}, it becomes {Cash: 400}
    

【问题讨论】:

  • 'current_assets`是什么数据结构?
  • 如果current_assets[key] 是一个浮点值,你不能append 另一个浮点数。相反,该值应该是一个列表,其中包含一个或多个浮点数。
  • @尼克字典
  • @JohnGordon 我修复了那个部分,它仍然显示 [200, 200] 而不是 [100, 200] 的列表

标签: python dictionary while-loop append


【解决方案1】:

请让我们使用 collections 包中的 defaultdict,然后将其转换为 dict:

from collections import defaultdict
data = defaultdict(list)
print(data)
#defaultdict(<class 'list'>, {})
data[1].append(10.5)
print(data)
#defaultdict(<class 'list'>, {1: [10.5]})
data[1].append(10.5)
print(data)
print(dict(data))
#defaultdict(<class 'list'>, {1: [10.5, 10.5]})
#{1: [10.5, 10.5]}

【讨论】:

猜你喜欢
  • 2019-06-08
  • 2020-04-12
  • 2013-10-11
  • 1970-01-01
  • 1970-01-01
  • 2013-09-19
  • 1970-01-01
  • 2021-12-24
  • 1970-01-01
相关资源
最近更新 更多