'Create Dictionary with byte keys (based on strings)

How can directly create a dict with byte keys in a list comprehension?

I've tried it with fstrings and a byte conversion but a shorter version would be nice.

expression:

_dict = {bytes(f"test_{_i}", encoding="utf-8"): _i for _i in range(0, 1)}

Result:

_dict = {b'test_0': 0}


Solution 1:[1]

What about the str.encode method, like this:

_dict = {f"test_{_i}".encode(): _i for _i in range(0, 1)}

Note: in order to make it shorter you can skip the explicit declaration of the encoding as "utf-8", since that is the default encoding anyways.

Solution 2:[2]

You could use a bytes string and percent formatting:

_dict = {b"test_%d" % _i: _i for _i in range(0, 1)}
print(_dict)

Output:

{b'test_0': 0}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Szabolcs
Solution 2 Terry Spotts