0

How to take the dict into .txt file, when my keys are tuple?

When my keys are int, it can run successfully.

But when the keys are tuple, it fails.

dict = {(1, 1): 11, (2, 2): 22, (3, 3): 33, (4, 4): 44, (5, 5): 55, (6, 6): 66, (7, 7): 77, (8, 8): 88, (9, 9): 99}

import json
with open('dict.txt', 'w') as file:
    file.write(json.dumps(dict))

TypeError: keys must be str, int, float, bool or None, not tuple
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
Drizzle
  • 95
  • 1
  • 6

2 Answers2

0

You could convert the keys to strings.

new_dict = {}
for k,v in dict.items():
    new_dict[str(k)] = v

Then you could write the new_dict to the text file.

areobe
  • 167
  • 10
0

You can convert your tuple to string before loading into json:

dict = {(1, 1): 11, (2, 2): 22, (3, 3): 33, (4, 4): 44, (5, 5): 55, (6, 6): 66, (7, 7): 77, (8, 8): 88, (9, 9): 99}

import json

def map_dict(d):
    return {str(k): v for k, v in d.items()}


with open('dict.txt', 'w') as file:
    file.write(json.dumps(map_dict(dict)))

Or you can directly convert dict to str:

dict = {(1, 1): 11, (2, 2): 22, (3, 3): 33, (4, 4): 44, (5, 5): 55, (6, 6): 66, (7, 7): 77, (8, 8): 88, (9, 9): 99}

with open('dict.txt', 'w') as file:
    file.write(str(dict))
Dharman
  • 30,962
  • 25
  • 85
  • 135
Rish
  • 804
  • 8
  • 15