【问题标题】:how to achieve the following result using dict comprehension?如何使用dict理解实现以下结果?
【发布时间】:2019-03-13 18:41:21
【问题描述】:

您好,我想从字典中获取所有“整数”值:

array_test = [{ "result1" : "date1",  "type" : "Integer"},{ "result1" : "date2", "type" : "null"}]

我试过了:

test = {'result1':array_test['result1'] for element in array_test if array_test['type'] == "Integer"}

但是我得到了这个错误:

>>> test = {'result1':array_test['result1'] for element in array_test if array_test['type'] == "Integer"}

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <dictcomp>
TypeError: list indices must be integers or slices, not str
>>> 
>>> 

所以我想感谢支持以实现以下输出

test = [{ "result1" : "date1",  "type" : "Integer"}]

【问题讨论】:

    标签: python python-3.x dictionary list-comprehension


    【解决方案1】:

    你需要一个列表理解,而不是字典理解:

    array_test = [{ "result1" : "date1",  "type" : "Integer"},{ "result1" : "date2", "type" : "null"}]
    
    test = [x for x in array_test if x['type'] == 'Integer']
    # [{'result1': 'date1', 'type': 'Integer'}]
    

    为什么?因为所需的输出是一个列表(字典列表)。

    【讨论】:

    • 非常感谢您的支持
    猜你喜欢
    • 1970-01-01
    • 2014-10-29
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 2019-12-23
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多