'How to take the dict into .txt file, when my keys are tuple? [duplicate]
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
Solution 1:[1]
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))
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dharman |
Solution 2 | areobe |