0

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'
}
Billy Jacobson
  • 1,608
  • 2
  • 13
  • 21
  • Please explain little more >>> {b'cf1:c1': b'test-value'} {'cf1:c1': 'test-value'} >>> a = {b'cf1:c1': b'test-value'} >>> a {'cf1:c1': 'test-value'} – aibotnet Aug 08 '18 at 20:39
  • `print({b'cf1:c1': b'test-value'})`? This works in python3 – Gillespie Aug 08 '18 at 20:40
  • `json.dumps` doesn't work because python dictionaries are not JSON. You would need to first convert your dictionary to JSON first. – Gillespie Aug 08 '18 at 20:41

1 Answers1

1

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.

Jacob Rodal
  • 620
  • 1
  • 6
  • 12