如何确保使用 for 循环在字典中为 Python 创建正确的 key:value 对并尝试 except?

How to make sure to create the correct key:value pair in dictionary for Python with for loops and try except?

在将元素添加回字典时,我正在尝试执行下面的粗体行,但我想确保它正在执行我希望它执行的操作。我也将 csv 文本放在底部。我想确保如果相同的收入类型多次出现,我的函数将能够捕获它,并且我的函数会忽略带有 try 和 except below 的缺失或无效金额的收入。

遍历列表中的每一行

for line in lines:

    # strip white spaces in the line
    line = line.strip()

    # split items in the line by :
    income_list = line.split(':')

    # if empty amount, skip the line
    if len(income_list) <= 1:
        continue

    # set the type and amount as a variable and strip white space
    income_type = income_list[0].strip()
    total_income_amount = income_list[1].strip()

    # try and except to catch invalid amount
    try:
        total_income_amount = float(total_income_amount)
        
        **#add income type and amount to income dictionary** 
        income[income_type] = income.get(income_type, 0) + total_income_amount
    except ValueError:
        continue

如果这是csv中的收入列表:但是我们希望能够按照输入的费用类型进行排序。

库存:10000 房地产:2000 工作:80000 投资:30000 库存:20000 investment:1000 捐款: 合约:sss

感谢您的帮助!

records = []  # for storing line data

for line in lines:

    # Need to split correctly first.
    income_list = line.strip().replace(": ", ":").split(" ") # ['stock:10000', 'estate:2000', ...]

    # loop over each income data of the line
    income = {}
    for i in income_list:

        # get type and amount
        income_type, income_amount = [tmp.strip() for tmp in i.strip().split(":")]

        # try if the value is valid
        try:
            if income_type not in income.keys():
                income[income_type] = float(income_amount)
            else:
                income[income_type] += float(income_amount)
        except:
            continue
    
    # save this line data to the records
    records.append(income)

# do your sorting here as needed with 'records'
# keep in mind not all data have the same keys
# so you need to deal with null key values

# for example assuming all data has the key "stock"
sorted_by_stock_asc = sorted(records, key=lambda x: x["stock"])