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

在将元素添加回字典时,我尝试执行下面的粗体行,但我想确保它正在执行我想要的操作。我也将 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


感谢您的帮助!


MYYA
浏览 59回答 1
1回答

慕桂英546537

records = []&nbsp; # for storing line datafor line in lines:&nbsp; &nbsp; # Need to split correctly first.&nbsp; &nbsp; income_list = line.strip().replace(": ", ":").split(" ") # ['stock:10000', 'estate:2000', ...]&nbsp; &nbsp; # loop over each income data of the line&nbsp; &nbsp; income = {}&nbsp; &nbsp; for i in income_list:&nbsp; &nbsp; &nbsp; &nbsp; # get type and amount&nbsp; &nbsp; &nbsp; &nbsp; income_type, income_amount = [tmp.strip() for tmp in i.strip().split(":")]&nbsp; &nbsp; &nbsp; &nbsp; # try if the value is valid&nbsp; &nbsp; &nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if income_type not in income.keys():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; income[income_type] = float(income_amount)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; income[income_type] += float(income_amount)&nbsp; &nbsp; &nbsp; &nbsp; except:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; # save this line data to the records&nbsp; &nbsp; 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"])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python