python - 从字典列表中获取字典中键的值
问题描述
假设 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
解决方案
颠倒列表的顺序,以便首先检查最后一个元素
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
推荐阅读
- azure - 2021 后续问题将子域映射到虚拟目录 Azure WebApps
- api - 未从 Facebook 提要 webhook 接收数据
- java - 有没有办法甚至可以访问/耗尽java延迟队列中未过期的元素
- r - R system.file 不像记录的那样工作?(或者只是令人困惑?)
- excel - 仅循环一次过滤条件(已解决)
- angular - Angular Kendo UI Datepicker - 禁用两个日期范围
- python - 我怎么做才能让你不能用 echo 命令@everyone
- html - 试图做 iframe,但无法弄清楚
- python - 如何在 Python 中使用 1、2、3 等选项来实现不同的代码?
- python - 为什么我的对象总是变成 NoneType?