“行程”是词典的列表。在这种情况下,键“ trip_block”仅出现在第6个词典中。为什么这样不起作用:
trip[:]['trip_block']
TypeError: list indices must be integers or slices, not str
但这确实有效并返回值:
trip[5]['trip_block']
由于该键出现在不同的索引中,所以我真的很想使用trip [:]进行搜索。我正在尝试在if语句中使用它:
if trip[:]['trip_block']:
答案 0 :(得分:0)
我的建议是循环浏览您的列表。 [:]
变体仅获取列表中的所有字典。看看这个,看看它是否对您有用:
for dictionary in trip: #loop through list of dicts
if 'trip_block' in dictionary.keys(): #check if key is in this dict
print(dictionary['trip_block'])
break #end loop, don't use break if there's more than one dict with this key and you need them all
答案 1 :(得分:0)
trip[:]
是一个列表。试图像字典一样对其进行索引将无法正常工作。如果要获取包含“ trip_block”的字典的所有值的列表,请尝试:
[d['trip_block'] for d in trip if 'trip_block' in d]
答案 2 :(得分:0)
[:]
是一个切片,其作用取决于行程的类型。如果trip是一个列表,则此行将创建该列表的浅表副本。对于元组或str类型的对象,它将不执行任何操作(如果不使用[:],该行将执行相同操作),对于(例如)NumPy数组,它将为相同的数据创建一个新视图。
您可以改用以下内容:
trip = [
{"name": "name1", "trip_block__": 10},
{"name": "name2", "trip_block_": 5},
{"name": "name3", "trip_block": 7}
]
res1 = next(item for item in trip if 'trip_block' in item.keys())
print(res1)
res2 = list(filter(lambda trip_block: 'trip_block' in trip_block.keys(), trip))
print(res2)
第一种方法是找到具有所需密钥的dict
。
第二个过滤器过滤包含所需键的dict
答案 3 :(得分:0)
trip [:]表示您只获得整个列表的副本
您需要遍历列表...
,由于它出现在不同的索引中,因此您需要再次将其存储在列表中。
您可以像这样使用列表理解
trip_block_items = [item["trip_block"] for item in trip if "trip_block" in item]
或一个简单的for循环
trip_block_items = []
for item in trip:
if "trip_block" in item:
trip_block_items.append(item["trip_block"])