检查字典的链式实现中的值

时间:2016-11-20 04:08:39

标签: python python-3.x dictionary

我有一个字典,它使用具有相同键的值的链接,这意味着dict[key] = [object1, object2, object3,..., object n]

我有两个对象year0year1。我需要查找year0year1是否在某个键的字典中。

如果year0year1不可用,那么我应该继续下一个键。注意:year0year1是两个不同的对象。

不幸的是,我不断收到各种错误,例如在转让前引用的对象,或者我无法转到下一个密钥。

以下是我的代码,以获取更多信息:

rateLst = []
if year1 > year0: 
    for reg in data.keys():
        slots = data[reg] #slots = [(object[year, index]), object[year, index]
        for value in slots: #value = object[year, index]
            if value.year == year0: 
                index0 = value.index 
            if value.year == year1:
                index1 = value.index
        if index1 is None or index0 is None: #error occurs even if I initialize the values as well it doesn't work
            pass
        else:
            gRate = cagr([index0, index1], year1 - year0)
            rateLst.append((reg, gRate))
return rateLst

谢谢你< 3

1 个答案:

答案 0 :(得分:2)

rateLst = []
if year1 > year0: 
    index0, index1 = None, None
    for reg, slots in data.items():
        #slots = data[reg] #slots = [(object[year, index]), object[year, index]
        for value in slots: #value = object[year, index]
            if value.year == year0: 
                index0 = value.index 
            if value.year == year1:
                index1 = value.index
        if index1 is None or index0 is None: #error occurs even if I initialize the values as well it doesn't work
            pass
        else:
            # You are using OR operator above so there is a chance that index0 or index1 would be None, not sure if this is intended or not
            gRate = cagr([index0, index1], year1 - year0)
            rateLst.append((reg, gRate))
return rateLst