2

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 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.