如何在Python中访问字典的元素,其中键是字节而不是字符串

Sho*_*obi 4 python dictionary python-3.x

抱歉,如果这个问题太菜鸟了。

我有一本字典,其中的键是字节(如b'access_token')而不是字符串。

{
 b'access_token': [b'b64ssscba8c5359bac7e88cf5894bc7922xxx'], 
 b'token_type': [b'bearer']
}
Run Code Online (Sandbox Code Playgroud)

通常我通过访问字典的元素data_dict.get('key'),但在这种情况下我得到的是NoneType而不是实际值。

我如何访问它们或者有没有办法将此字节键控字典转换为字符串键控字典?

编辑:access_token=absdhasd&scope=abc我实际上是通过解析这样的查询字符串得到这个字典的urllib.parse.parse_qs(string)

Gre*_*Guy 5

您可以使用str.encode()bytes.decode()在两者之间交换(可选地,提供指定编码的参数。'UTF-8'默认情况下)。结果,你可以接受你的命令:

my_dict = {
 b'access_token': [b'b64ssscba8c5359bac7e88cf5894bc7922xxx'], 
 b'token_type': [b'bearer']
}
Run Code Online (Sandbox Code Playgroud)

只需进行理解即可交换所有键:

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

同样,您可以在访问 dict 时使用.encode(),以便从字符串中获取 bytes 对象:

my_key = 'access_token'
my_value = my_dict[my_key.encode()]
# [b'b64ssscba8c5359bac7e88cf5894bc7922xxx']
Run Code Online (Sandbox Code Playgroud)