小编use*_*520的帖子

列表索引必须是整数或切片,而不是字典

我正在做一些涉及从列表中提取数据的操作,其中每个元素都是一个字典。每个字典包含两个键值对,它们是一个字符串,然后是一个整数(即 {'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, …
Run Code Online (Sandbox Code Playgroud)

python dictionary list indices

0
推荐指数
1
解决办法
7835
查看次数

标签 统计

dictionary ×1

indices ×1

list ×1

python ×1