首页 > 解决方案 > 从字典列表中获取字典中键的值

问题描述

假设 dict_lst = dict 列表。我正在尝试返回与 dict_lst 中以参数 k 作为键的最新 dict 关联的值。如果 k 不在 dict_lst 中的任何 dict 中,我们必须引发 KeyError。我该怎么做?

def get_value(dict_lst, k):
   pass

例子:

dict_lst = [{'a':1, 'b':2, 'c':3}, {'c':4, 'd':5, 'e':6}, {'e':7, 'f':8, 'g':9}]

d['c'] --> 4(发现带有'c'的第二个字典是最新的字典)

d['y'] --> KeyError

标签: pythonloopsclassdictionary

解决方案


颠倒列表的顺序,以便首先检查最后一个元素

dict_lst = [{'a':1, 'b':2, 'c':3}, {'c':4, 'd':5, 'e':6}, {'e':7, 'f':8, 'g':9}]
def get_value(dict_lst, k):
    for i in dict_lst[::-1]:
        if k in i.keys():
            return i.get(k)
    raise KeyError
print(get_value(dict_lst,'c')) #returns 4
print(get_value(dict_lst,'m')) #returns KeyError

推荐阅读