你好,我想从字典中获取所有的'Integer'值:
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"}]
答案 0 :(得分:2)
您需要一个列表理解,而不是字典理解:
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'}]
为什么?因为所需的输出是一个列表(词典列表)。