【问题标题】:Get value of key in dict from a list of dictionaries从字典列表中获取字典中键的值
【发布时间】:2020-11-20 01:10:08
【问题描述】:

假设 dict_lst = 字典列表。我正在尝试返回与 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'的dict是最新的dict)

d['y'] --> KeyError

【问题讨论】:

    标签: python loops class dictionary


    【解决方案1】:

    这似乎有你正在寻找的行为:

    def get_value(dict_lst, k):
        values = list()
        for dl in dict_lst:
            try:
                values.append(dl[k])
            except KeyError:
                pass
        if len(values) == 0:
            raise KeyError()
        return values[-1]
    
    
    dict_lst = [{'a':1, 'b':2, 'c':3}, {'c':4, 'd':5, 'e':6}, {'e':7, 'f':8, 'g':9}]
    
    get_values(dict_lst, k='c') # returns 4
    get_values(dict_lst, k='y') # raises KeyError
    

    【讨论】:

      【解决方案2】:

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

      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
      

      【讨论】:

        猜你喜欢
        • 2022-06-21
        • 1970-01-01
        • 1970-01-01
        • 2019-03-27
        • 2013-08-22
        • 1970-01-01
        • 2020-03-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多