【问题标题】:How to index a list of dictionaries in python?如何在python中索引字典列表?
【发布时间】:2021-12-29 14:32:43
【问题描述】:

如果我在 python 脚本中有一个字典列表,我打算稍后在 JSON 文件中将 dump 作为对象数组,我如何索引列表中特定字典的键?

例子:

dict_list = [{"first_dict": "some_value"}, {"second_dict":"some_value"}, {"third_dict": "[element1,element2,element3]"}]

我的直观解决方案是dict_list[-1][0](例如,访问列表中最后一个字典的第一个键)。然而,这给了我以下错误:

IndexError: list index out of range

【问题讨论】:

  • 在您的示例中,'} 似乎放错了位置。
  • 虽然您的代码不是有效的python,但我想您正试图通过索引访问字典的键?

标签: python json dictionary indexing


【解决方案1】:

输入到字典中的键会选择一些值,格式为 dict = {0:some_value}

查找特定值:

list_dictionary = [{"dict1":'value1'},{"dict2","value2"}]
value1 = list_dictionary[0]["dict1"]

“键”是您从字典中查找值所必须使用的键

例子:

dictionary = {0:value}
dictionary[0]

在这种情况下它会起作用

但是要选择我们要做的元素

values = []

for dictionary in dict_list:
   for element in dictionary:
      values.append(dictionary[element])

输出:

['some_value', 'some_value', ['element1', 'element2', 'element3']]

【讨论】:

    【解决方案2】:
    dict_list = [{"first_dict": "some_value"}, {"second_dict":"some_value"}, {"third_dict": ['element1','element2','element3']}]
    

    如果你的 dict 看起来像这样,你也可以这样做

    dict_list[-1]["third_dict"]
    

    您不能使用 int 访问“第一个键”,因为您有一个 dict 您可以使用.keys() 获取第一个密钥,然后

    dict_list[-1].keys()[0]
    

    【讨论】:

    • 你的第一个解决方案dict_list[-1]["third_dict"] 给了我错误:KeyError: 'third_dict'。这是按照示例进行的,这是我正在测试的实际列表:individual_window_array = [{"window_numeric_name/driver_object_name":f'{window_numeric_name}'}, {"window_description":f'{current_window_description}'} ,{"window_tabs":f'{current_window_tabs}', "window_custom_title":f'{current_window_title}'}]
    • 试试 dict_list[-1][name of your first key](在你的情况下是 window_tabs)
    • 对不起,我的评论中有一个类型,它是[{"window_numeric_name/driver_object_name":f'{window_numeric_name}'}, {"window_description":f'{current_window_description}'} ,{"window_tabs":f'{current_window_tabs}'}, {"window_custom_title":f'{current_window_title}'}]。你是说试试"window_custom_title"
    • 是的,如果它可以在未来改变,你也应该做第二个选项
    • 第二个选项给出:TypeError: 'dict_keys' object is not subscriptable
    【解决方案3】:

    通过使用 dict_list[-1][0],您正在尝试使用您没有的列表访问列表。您有一个列表,其中包含一个 dict 键。

    以你的例子dict_list[-1][0]

    • 当您提及 dict_list 时,您已经“在列表中”。
    • 第一个索引 [-1] 指向列表的最后一项。
    • 只有在前一个索引中提到的项目是一个列表时,第二个索引才“可用”。因此出现错误。

    使用:

    dict_list=[{"first_dict": "some_value"}, {"second_dict":"some_value"},{"third_dict": [0,1,2]}]
    

    要访问 third_dict,您需要:

    for value in list(dict_list[-1].values())[0]:
        print(value)
    

    输出:

    0
    1
    2
    

    【讨论】:

      【解决方案4】:

      如果您知道字典键的顺序并且您使用的是最新的 python 版本之一(键保持相同的顺序),那么:

      
      dict_list = [
          {"first_dict": "some_value"}
          , {"second_dict":"some_value"}
          , {"third_dict": ["element1", "element2", "element3"]}
      ]
      
      first_key = next(iter(dict_list[-1].keys()))
      
      ### OR: value
      
      first_value = next(iter(dict_list[-1].values()))
      
      ### OR: both key and value
      
      first_key, first_value = next(iter(dict_list[-1].items()))
      
      
      print(first_key)
      print(first_key, first_value)
      print(first_value)
      

      【讨论】:

      • 使用它会给我错误:Convert a String to Variable Name in Python 当我通过这种方法运行它时:locals().update(first_value)。知道这意味着什么吗?谢谢。
      • @double_wizz 它不是字典,您不能将其更新为字典
      【解决方案5】:

      如果您有以下字典列表:

      dict_list = [{"key1":"val1", "key2":"val2"}, {"key10":"val10"}]
      

      然后要访问最后一个字典,您确实会使用 dict_list[-1] 但这会返回一个字典,该字典使用其键而不是数字进行索引:dict_list[0]["key1"]

      要仅使用数字,您需要先获取键列表:list(dict_list[-1])。这个列表的第一个元素list(dict_list[-1])[0] 将是第一个键"key10"

      然后您可以使用索引来访问最后一个字典的第一个键:

      dict_index = -1
      key_index = 0
      
      d = dict_list[dict_index]
      keys = list(d)
      val = d[keys[key_index]]
      

      但是您会将字典用作列表,因此列表列表可能比字典列表更适合。

      【讨论】:

      • 第一个建议:list(dict_list[-1])[0] 在我尝试将输出包含在变量中时给了我以下错误:ValueError: dictionary update sequence element #0 has length 1; 2 is required 我不确定这意味着什么。谢谢。
      • 我更新了代码部分,检查您是否以类似的方式存储提取的值。但是您的错误听起来像是您将提取的值传递给需要字典的函数,所以我认为问题在于代码的其余部分
      猜你喜欢
      • 1970-01-01
      • 2021-02-27
      • 2015-07-03
      • 1970-01-01
      • 1970-01-01
      • 2022-11-12
      • 1970-01-01
      • 2014-09-17
      • 1970-01-01
      相关资源
      最近更新 更多