Search code examples
pythonstringpython-3.xpprint

How to print a Python dict containing byte strings?


I've got a dictionary with keys as byte strings and values as byte strings and would like to print a cleaned up version of it. Here is an example pair:

{b'cf1:c1': b'test-value'}

I've tried doing json.dumps, but I get an error saying that

TypeError: key b'cf1:c1' is not a string

I've also tried pprint. Are there any libraries or easy ways to do this?

Ideally the result would look like

{
    'cf1:c1': 'test-value'
}

Solution

  • You can create a new dictionary with decoded keys and values like so:

    x = {b'cf1:c1': b'test-value'}
    y = {k.decode("utf-8"):v.decode("utf-8") for k,v in x.items()}
    

    Then you should be able to display y as you desire.