Question

I'm trying to use a string containing unicode as a dictionary key but I am getting this error:


print title

1 - Le chant du départ (Gallo, Max)

print repr(title)

'1 - Le chant du d\xc3\xa9part (Gallo, Max)'

d[title].append([infos,note])

KeyError: '1 - Le chant du d\xc3\xa9part (Gallo, Max)'

Can we use a string containing a unicode characters as a key or do we have to do some encoding first?

Was it helpful?

Solution

The error you are receiving is a KeyError, indicating that the key is not present in your dict (https://wiki.python.org/moin/KeyError). When you write

d[title].append([infos,note])

The interpreter is looking for an existing key in your dictionary of title. Instead, you should do:

if title in d:
    d[title].append([infos, note])
else:
    d[title] = [infos, note]

This checks first to see if the key exists in the dictionary. If so, it means that a list is already there, and so it tacks on those values. If not, it creates a new list with those values.

Once you have the hang of that, you can look into the collections module for a default dict (http://docs.python.org/2/library/collections.html). You could then do something like:

from collections import defaultdict
d = defaultdict(list)
...
d[title].append([infos, note])

Now you won't get a KeyError, because defaultdict is assuming a list if the key doesn't exist.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top