0

I'm new to python and I was wondering if there's a way for me to pull a value at a specific index. Let's say I have a key with multiple values(list) associated with it.

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

Let's say I want to iterate through values and print out the value if it's equal to 'DOG'. Do Values, Key pairs have a specific index associated with the position of Values?

I've try reading up on dict and how it works apparently you can't really index it. I just wanted to know if there's a way to get around that.

Saleem Ali
  • 1,363
  • 11
  • 21
Vathana Him
  • 31
  • 1
  • 4

4 Answers4

2

You can perform the following (comments included):

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.
RamWill
  • 288
  • 1
  • 3
  • 6
1

So maybe this will help:

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.

You can use this:

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")
Sid
  • 2,174
  • 1
  • 13
  • 29
  • 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. – Vathana Him Oct 07 '19 at 14:14
1

Keys and values in a dictionary are indexed by key and do not have a fixed index like in lists.

However, you can leverage the use of 'OrderedDict' to give an indexing scheme to your dictionaries. It is seldom used, but handy.

That being said, dictionaries in python3.6 are insertion ordered :

More on that here :

Are dictionaries ordered in Python 3.6+?

Cyrus Dsouza
  • 883
  • 7
  • 18
0
d = {'animal': ['cat', 'dog', 'kangaroo', 'monkey'], 'flower': ['hibiscus', 'sunflower', 'rose']}
    for key, value in d.items():
        for element in value:
            if element is 'dog':
                print(value)

does this help? or, you want to print index of key in dictionary?

Prem Ib
  • 136
  • 2
  • 11