我正在做一些操作,涉及从列表中提取数据,其中每个元素都是字典。每个字典包含两个键值对,它们是一个字符串,然后是一个int(即{'ID':0,'Zip Code':9414}),然后是一个键值对,其中键是一个字符串,然后一个列表({'Value':[0,0,1,1,0,1]})列表索引必须是整数或切片,而不是字典
我能够非常容易地访问列表中的列表中的字典列表中的值。但是,由于列表中有许多元素,我必须使用for循环来完成它。基本上我的方法是检查1是否在列表中的字典中的索引(用户指定的数字)在该列表中。如果是,它会使用同一个字典中的前两个键值对更新另一个列表。
所以,像这样:
import returnExternalList #this method returns a list generated by an external method
def checkIndex(b):
listFiltered = {}
listRaw = returnExternalList.returnList #runs the method "returnList", which will return the list
for i in listRaw:
if listRaw[i]['Value'][b] == 1:
filteredList.update({listRaw[i]['ID']: listRaw[i]['Zip Code']})
print(filteredList)
checkIndex(1)
returnExternalList.returnList:
[{'ID':1 ,'Zip Code':1 ,'Value':[0,1,0,0,1]},{'ID':2 ,'Zip Code':2 ,'Value':[0,0,0,0,0]},{'ID':3,'Zip Code':3 ,'Value':[0,1,1,1,0]},{'ID':4 ,'Zip Code':4 ,'Value':[1,0,0,0,0]}]
expected output:
[{1:1 , 3:3}]
我可以很简单地只是做这个列表中的访问值的字典里面的列表里外的一个 for循环:
print(listRaw[0]['Value'][1]) would return 1, for example.
但是,当试图用for循环复制该行为以检查列表中的每一个行为时,出现错误:
TypeError: list indices must be integers or slices, not dict
我该怎么办?
编辑:既然有人问了,returnExternalList:
def returnList:
listExample = [{'ID':1 ,'Zip Code':1 ,'Value':[0,1,0,0,1]},{'ID':2 ,'Zip Code':2 ,'Value':[0,0,0,0,0]},{'ID':3,'Zip Code':3 ,'Value':[0,1,1,1,0]},{'ID':4 ,'Zip Code':4 ,'Value':[1,0,0,0,0]}]
return listExample
编辑:我用了两个下方所提供的解决方案,虽然它确实摆脱错误的(谢谢!)输出仅仅是一个空白字典。
代码:
for i in listRaw:
if i['Value'][b] == 1:
filteredList.update({i['ID']: i['Zip Code']})
or
for i in range(len(listRaw):
if listRaw[i]['Value'][b] == 1:
filteredList.update({listRaw[i]['ID']: listRaw[i]['Zip Code']})
编辑:
它现在,该列表是空的原因是因为我比较1为 '1'。它已被修复。谢谢。
可以共享整个错误堆栈? – glls
@glls我100%肯定它的工作原理,因为当我尝试从returnExternalList打印列表中的这个方法,它的工作原理。我会更新它只是为了确保。 – user132520
看起来像你想的类型错误指示遍历一个字典... – glls