简体   繁体   English

如果 dict 值的位数超过指定的位数,则引发错误

[英]Raising an error if a dict value has more than specified number of digits

I'm trying to raise an error if a value in a dict has greater than eg 6 digits (would be useful to test for a particular number of decimal places too).如果 dict 中的值大于例如 6 位(对于测试特定的小数位数也很有用),我试图引发错误。

eg for the dict below (and say number digits = 6)例如对于下面的字典(并说数字= 6)

example_dict = {'dict_id': 12345,
                 'key1': 10501.04999999999999999262}
for key, value in tariff_detail.items():
    if value == type(float) and (test for number of digits):
        raise ValueError("DictID: {}, Key Missing: {}".format(example_dict['dict_id'],key))

(Note if I stick the above example in ipython and do example_dict.values() it pops out [10501.05] - Is there in built rounding or is this just for display?) (请注意,如果我在 ipython 中粘贴上面的示例并执行 example_dict.values() 它会弹出 [10501.05] - 是否存在内置舍入还是仅用于显示?)

What's the best way to test for the number of digits and raise an error on fail?测试位数并在失败时引发错误的最佳方法是什么?

一种简单的方法是将值转换为字符串,然后计算其长度:

if len(str(value)) > 6 :

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python in Huffman encoding error when the numbers are more than 10 - Python in huffman coding error when the number of digits are more than 10 给定 n,取 n 的数字之和。 如果该值超过一位,则继续减少产生一位数 - Given n, take tsum of the digits of n. If that value has more than one digit, continue reducing a single-digit number is produced 通过networkx引发`NetworkXError:节点8没有位置`错误,不能绘制8个以上的节点 - Can not draw more than 8 nodes by networkx raising `NetworkXError: Node 8 has no position` error Python Dict超过一个Max值 - Python Dict more than one Max value 正则表达式捕获超过4位数的任何数字之前的重叠匹配 - regex to capture overlapping matches preceding any number with more than 4 digits 如何找到具有更多填充值的字典? - How to find the dict which has more number of filled values? Pandas 如果列值根据值出现超过一定次数,则删除行 - Pandas drop row if column value has appeared more than some number of times depending on the value 如何将 key:value 添加到 empy dict 中,值大于 1 个项目 - how to add in key:value into empy dict with values be more than 1 items 如何在Python中从嵌套字典打印多个值 - How to print more than one value from nested dict in Python Dict-如果每个键有多个值,则提取最后一个元素 - Dict - If more than one value per key, extract the last element
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM