如何返回给定特定值的字典中的上一个键?

时间:2019-08-07 08:30:30

标签: python python-3.x

对于不同的收入水平,我有不同的税率。

我正在尝试从函数获取的税率中返回“最大”值。如何获得返回“最大”值的值?

tax_levels = [
{
    "min": 0,
    "max": 999,
    "rate": 1,
},
{
    "min": 1000,
    "max": 1999,
    "rate": 5
},
]

current_rate = 5
max_current_rate = ??

def max_current_rate(current_rate, tax_levels):
for index, tax_level in enumerate(tax_levels):
    if tax_level['rate'] == current_rate:
        max_current_rate = tax_levels[index]['rate'] #I am trying to 'rate' -1
        return max_current rate

我尝试了for循环...试图在循环中使'rate'-1。 我正在尝试使用变量current_rate使它返回到max_current_rate的1999。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

是什么阻止您从要迭代的当前项目中抓取max键?

def max_current_rate(current_rate, tax_levels):
    for index, tax_level in enumerate(tax_levels):
        if tax_level['rate'] == current_rate:
            max_current_rate = tax_level['max']
            return max_current_rate

在循环中,tax_level将是字典之一,因此您可以访问其ratemax值。

答案 1 :(得分:0)

我不确定我是否理解您的问题并且您的问题正确。我假设您想在rate中获得最高的tax_levels值。因此,您需要使用List正确处理Dicts

tax_levels = [
{
    "min": 0,
    "max": 999,
    "rate": 1
},
{
    "min": 1000,
    "max": 1999,
    "rate": 5
},
]

current_rate = 5

def Func(Rate, TaxLevels):
  for Level in TaxLevels:
      if Level['rate'] == Rate:
          return Level['rate']

print(Func(current_rate, tax_levels))

此代码导致

>> 5