Create Dictionary with byte keys (based on strings)

Viewed 45

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}
2 Answers

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.

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}
Related