为什么字典python中缺少最后一个键

时间:2020-07-03 15:54:07

标签: python dictionary

代码在下面

from decimal import Decimal
sample = [
    ("Book", Decimal("10.000"), Decimal("0E-20"), None),
    ("Pen", Decimal("66.66666"), Decimal("0E-20"), None),
    ("Pencil", Decimal("100.0000"), Decimal("0E-20"), '133.33'),
]


datalst=[]    

for i in sample:
    data = {} 
    try:
        if i[0] is not None:
            data['prod'] = i[0]
        else:
             data['prod'] = 0
        if i[1] is not None:
            data['test1'] = round(i[1])
        else:
             data['test1'] = 0
        if i[2] is not None:
            data['test2'] = round(i[2])
        else:
             data['test2'] = 0
        if i[3] is not None:
            data['test3'] = round(i[3])
        else:
             data['test3'] = 0
    except:
        
        pass   
    datalst.append(data)  

print(datalst)

当前输出

[{'prod': 'Book', 'test1': 10, 'test2': 0, 'test3': 0}, {'prod': 'Pen', 'test1': 67, 'test2': 0, 'test3': 0}, {'prod': 'Pencil', 'test1': 100, 'test2': 0}]

预期中

[{'prod': 'Book', 'test1': 10, 'test2': 0, 'test3': 0}, {'prod': 'Pen', 'test1': 67, 'test2': 0, 'test3': 0}, {'prod': 'Pencil', 'test1': 100, 'test2': 0, 'test3':133}]

字典test3':133中缺少最后一个键

1 个答案:

答案 0 :(得分:2)

您有try: ... except: pass并定义了'133.33',它是一个直接与除外字符串匹配的字符串:通过round()函数放入时通过。先将字符串转换为十进制,然后一切正常

from decimal import Decimal
sample = [
    ("Book", Decimal("10.000"), Decimal("0E-20"), None),
    ("Pen", Decimal("66.66666"), Decimal("0E-20"), None),
    ("Pencil", Decimal("100.0000"), Decimal("0E-20"), '133.33'),
]

datalst = [{"prod":i[0], "test1":round(i[1]), "test2":round(i[2]), 
            "test3":round(Decimal(i[3])) if i[3] is not None else 0} for i in sample]

print(datalst)