【发布时间】:2016-09-19 18:55:18
【问题描述】:
我正在做一些涉及从每个元素都是字典的列表中提取数据的操作。每个字典包含两个键值对,它们是一个字符串,然后是一个 int(即 {'ID':0, 'Zip Code':9414}),然后是一个键值对,其中键是一个字符串,然后一个列表({'Value':[0,0,1,1,0,1]})
我可以很容易地在列表中的字典中访问该列表中的值。但是,由于列表中有一堆元素,我必须使用 for 循环来遍历它。基本上,我的方法所做的是检查 1 是否在列表中的 dict 中的索引(用户指定的数字)处。如果是,它会使用同一个字典中的前两个键值对更新另一个列表。
所以,像这样:
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 循环的列表 outside 内的字典内的列表中的值:
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 我 100% 确定它有效,因为当我尝试在此方法中从 returnExternalList 打印列表时,它有效。为了确定,我会更新它。
-
看起来你正试图迭代一个字典,因为 TypeError 表明......
标签: python list dictionary indices