Python:如果在while循环中存在键,添加到现有的字典值吗?

时间:2018-12-01 23:50:58

标签: python dictionary while-loop append

我现在有此代码。

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}
    

1 个答案:

答案 0 :(得分:0)

请让我们使用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]}