Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access elements of a dictionary in python where the keys are bytes instead of strings

Sorry if it's too much of a noob question.

I have a dictionary where the keys are bytes (like b'access_token' ) instead of strings.

{
 b'access_token': [b'b64ssscba8c5359bac7e88cf5894bc7922xxx'], 
 b'token_type': [b'bearer']
}

usually I access the elements of a dictionary by data_dict.get('key'), but in this case I was getting NoneType instead of the actual value.

How do I access them or is there a way to convert this bytes keyed dict to string keyed dict?

EDIT: I actually get this dict from parsing a query string like this access_token=absdhasd&scope=abc by urllib.parse.parse_qs(string)

like image 619
Shobi Avatar asked Oct 19 '25 10:10

Shobi


2 Answers

You can use str.encode() and bytes.decode() to swap between the two (optionally, providing an argument that specifies the encoding. 'UTF-8' is the default). As a result, you can take your dict:

my_dict = {
 b'access_token': [b'b64ssscba8c5359bac7e88cf5894bc7922xxx'], 
 b'token_type': [b'bearer']
}

and just do a comprehension to swap all the keys:

new_dict = {k.decode(): v for k,v in my_dict.items()}
# {
#   'access_token': [b'b64ssscba8c5359bac7e88cf5894bc7922xxx'], 
#   'token_type': [b'bearer']
# }

Similarly, you can just use .encode() when accessing the dict in order to get a bytes object from your string:

my_key = 'access_token'
my_value = my_dict[my_key.encode()]
# [b'b64ssscba8c5359bac7e88cf5894bc7922xxx']
like image 140
Green Cloak Guy Avatar answered Oct 21 '25 23:10

Green Cloak Guy


Most probably, you are making some silly mistake. It is working fine in my tests.
Perhaps you forgot to add the prefix b when trying to index the dictionary

d={
 b'key1': [b'val1'], 
 b'key2': [b'val2']
}

d[b'key1']     # --> returns [b'val1']
d.get(b'key2') # --> returns [b'val2']
like image 29
ePi272314 Avatar answered Oct 22 '25 00:10

ePi272314



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!