use*_*520 0 python dictionary list indices
我正在做一些涉及从列表中提取数据的操作,其中每个元素都是一个字典。每个字典包含两个键值对,它们是一个字符串,然后是一个整数(即 {'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}]
Run Code Online (Sandbox Code Playgroud)
只需执行以下操作,我就可以非常简单地访问 for 循环外列表内的字典内列表中的值:
print(listRaw[0]['Value'][1]) would return 1, for example.
Run Code Online (Sandbox Code Playgroud)
但是,当尝试使用 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
Run Code Online (Sandbox Code Playgroud)
编辑:我使用了下面提供的两个解决方案,虽然它确实消除了错误(谢谢!),但输出只是一个空白字典。
代码:
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']})
Run Code Online (Sandbox Code Playgroud)
编辑:
它现在有效,列表为空的原因是因为我正在比较 1 和 '1'。它已被修复。谢谢你。
当你做
for i in listRaw:
Run Code Online (Sandbox Code Playgroud)
在i没有索引,它在列表中的实际项目(在你的情况下,它是一个字典)
因此,您无需执行任何操作listRaw[i]即可获得该物品。i本身就是项目。相应地更改您的代码