Omer Lubin
Omer Lubin

Reputation: 679

(Python) Dictionary not recognizing keys

This is probably a stupid one. So, I have this dictionary, which includes a few keys. When I print the keys (as a list),

keys = list(dict.keys())
print(keys)

I get the output:

[b'batch_label', b'labels', b'data', b'filenames']

So far so good. But, when I try to access one of them,

return dict['labels']

I get a key error ('labels'). Why is that?

Upvotes: 1

Views: 1642

Answers (1)

rafaelc
rafaelc

Reputation: 59274

Your keys are not strings, but bytes objects. Thus, you should access them as bytes

x[b'label']

Notice that

>>> b'label' is'label'
False
>>> b'label' == 'label'
False

If you don't want to access this way, you can decode them to strings by specifying an encoding type. For example,

new_dict = {k.decode('utf-8'): v for k,v in x.items()}

Now you can do

new_dict['label']

Upvotes: 4

Related Questions