David Edmondson
David Edmondson

Reputation: 3

Convert a dict stored as a string to byte

I have been using osmnx for a project and have attempted to export the resulting dicts to csv using Python 3 using the following code:

with open('dict.csv', 'wb') as csv_file:
    writer = csv.writer(csv_file)
    for key, value in mydict.items():
       writer.writerow([key, value])

Unfortunately, I receive the error:

a bytes-like object is required, not 'str'

The code that is generating the dict is:

mydict = {num:list(streets_per_node.values()).count(num) for num in range(max(streets_per_node.values()) + 1)}

I have tried to hunt down the solution, but I fear either the answer is either too simple or too unusual to find in typical tutorials.

Upvotes: 0

Views: 269

Answers (1)

tzaman
tzaman

Reputation: 47790

open('dict.csv', 'wb') tells Python you want to open the file for writing bytes, not text, which is why you get that error. Just omit the b and it should work.

See: https://docs.python.org/3/library/csv.html#examples

Upvotes: 2

Related Questions