簡體   English   中英

無法從文件中讀取帶有元組鍵的字典

[英]Unable to Read Dictionary with Tuple Key from File

我有一本以元組為鍵的字典。

my_dictionary[k1, k2] = val

我將字典保存到文件中,但是當我讀回文件時出現錯誤。

dictionary_from_file = dict(dictionary_file.read())

錯誤:

ValueError: dictionary update sequence element #0 has length 1; 2 is required

Python字典構造函數不接受字符串(或將其解析為新字典)。

此外,當以元組為鍵時,您可以將其用作以下內容:

dict[(t1,t2)]=v

您可以采取以下步驟,並使用ast.literal_eval從字符串表示中取回字典:

import ast

# Create dictionary
dict1 = dict()

# Set values to tuple keys
dict1[(1,2)] = 'one two'
dict1[(3,4)] = 'three four'

# {(1, 2): 'one two', (3, 4): 'three four'}
dict_string = str(dict1)
print(dict_string)

# Restore dictionary from string with `ast.literal_eval`
dict2 = ast.literal_eval(dict_string)

# {(1, 2): 'one two', (3, 4): 'three four'}
print(dict2)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM