Как достичь следующего результата, используя dict понимание? - PullRequest
0 голосов
/ 13 марта 2019

Здравствуйте, я бы хотел получить все значения типа "Integer" из dict:

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

1 Ответ

2 голосов
/ 13 марта 2019

Вам нужно понимание списка, а не словарь:

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

Почему? Поскольку требуемый вывод - это список (список словарей).

...