Raëgan
Raëgan

Reputation: 17

AttributeError in dictionary

I found a way that can possibly allow me to get the keys of my dictionary using value with this :

mydic.keys()[mydic.values().index(value)]

My code is below:

def déchiffrement(code, dico):
    taille3 = len(code)
    décodé = []
    for i in range(taille3):
        décodé.insert(i, dico.keys()[dico.values().index(code[i])])
    return décodé

dico is a dictionary looking like this:

dico = {
    "A": [1, 9],
    "B": [12, 19],
    ...
    "Z": [78, 108],
}

and code is a list of numbers that corresponds to a letter. The numbers in dico are never the same.

However, I get an

AttributeError: 'dict_values' object has no attribute 'index'

which I don't understand because this code seems to work on other people's codes.

Upvotes: 0

Views: 993

Answers (2)

Igor Raush
Igor Raush

Reputation: 15240

Orange's answer and the comments on your question comments are correct; you are (presumably) using Python 3, where dict.values() returns a dictionary view object instead of a list, and does not provide the index() function.


However, it appears that you are looking to map every code separately back to the original character. For this, it is much cleaner to pre-compute the decoder:

def invert(dico):
    # map values to keys, note the nested comprehension
    return {i: k for k, v in dico.items() for i in v}

def decipher(code, dico):
    # note that this result can be cached or even just
    # computed outside the function
    decoder = invert(dico)

    # pass each code through the decoder map
    return [decoder[c] for c in code]

print decipher([1, 9, 108], {
    'A': [1, 9],
    'B': [12, 19],
    'C': [78, 108]
})

which outputs

['A', 'A', 'C']

Upvotes: 1

Aaron Christiansen
Aaron Christiansen

Reputation: 11837

index is a function of list, not of a dict_values object returned by dico.values(). So, change your code so that dico.values() is converted to a list:

def déchiffrement(code,dico):
    taille3 = len(code)
    décodé = []
    for i in range(taille3):
        décodé.insert(i, dico.keys()[list(dico.values()).index(code[i])]) # Changed here
    return décodé

Upvotes: 0

Related Questions