這個問題在這里已經有了答案: JSON 序列化以元組為鍵的字典 (9 個回答) 1 小時前關閉。
怎么拿dict進去.txt file,當我的鑰匙在tuple?
當我的密鑰是 時int,它可以成功運行。
但是當鍵是 時tuple,它失敗了。
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
uj5u.com熱心網友回復:
您可以將鍵轉換為字串。
new_dict = {}
for k,v in dict.items():
new_dict[str(k)] = v
然后你可以將 new_dict 寫入文本檔案。
uj5u.com熱心網友回復:
您可以在加載到 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)))
或者你可以直接將dict轉換為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))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/348996.html
上一篇:有沒有辦法在python中為參與者-組織者構建一個共現(頻率)矩陣?
下一篇:如何洗掉串列中的字典元素?
