簡體   English   中英

如何使用dict理解獲得以下結果?

[英]how to achieve the following result using dict comprehension?

您好,我想從字典中獲取所有“整數”值:

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"}]

您需要一個列表理解,而不是字典理解:

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'}]

為什么? 因為所需的輸出是一個列表(詞典列表)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM