一个键上有多个值的索引Dict

2024-05-29 11:46:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的新手,我想知道是否有一种方法可以让我在特定的索引中提取一个值。假设我有一个具有多个值(list)的键。你知道吗

d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}

假设我想遍历值并打印出值,如果它等于'DOG'。值、键对是否有与值的位置相关联的特定索引?你知道吗

我试着读一下dict和它的工作原理,显然你不能真正地索引它。我只是想知道有没有办法解决这个问题。你知道吗


Tags: 方法dictlistcat原理hedgehogdogfish
3条回答

所以也许这会有帮助:

d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}
for item in d:
    for animal in (d[item]):
        if animal == "DOG":
            print(animal)

Update -What if I want to compare the string to see if they're equal or not... let say if the value at the first index is equal to the value at the second index.

您可以使用:

d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}
for item in d:
    for animal in (d[item]):
        if animal == "DOG":
            if list(d.keys())[0] == list(d.keys())[1]:
                 print("Equal")
            else: print("Unequal")

您可以执行以下操作(包括注释):

d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}

for keys, values in d.items(): #Will allow you to reference the key and value pair
    for item in values:        #Will iterate through the list containing the animals
        if item == "DOG":      
            print(item)
            print(values.index(item))  #will tell you the index of "DOG" in the list.

字典中的键和值是按键索引的,不像列表中那样有固定的索引。你知道吗

但是,您可以利用“OrderedDict”为词典提供索引方案。它很少使用,但很方便。你知道吗

也就是说,python3.6中的词典是按插入顺序排列的:

更多信息请参见:

Are dictionaries ordered in Python 3.6+?

相关问题 更多 >

    热门问题