为了账号安全,请及时绑定邮箱和手机立即绑定

如何确保使用 for 循环和 try except 在 Python 字典中创建正确的键:值对?

如何确保使用 for 循环和 try except 在 Python 字典中创建正确的键:值对?

MYYA 2023-10-18 15:46:32
在将元素添加回字典时,我尝试执行下面的粗体行,但我想确保它正在执行我想要的操作。我也将 csv 文本放在底部。我想确保,如果相同的收入类型出现多次,我的函数将能够捕获它,并且我的函数会通过下面的 try 和 except 忽略缺少或无效金额的收入。迭代列表中的每一行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 投资:1000 捐赠:合同:sss感谢您的帮助!
查看完整描述

1 回答

?
慕桂英546537

TA贡献1848条经验 获得超10个赞

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"])


查看完整回答
反对 回复 2023-10-18
  • 1 回答
  • 0 关注
  • 56 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信