如何将文本文件中的多值字典作为字典导入python,以及可能出现的问题.需要答案



我是编程新手。

我有一个带字典的文本文件。

{1: [1, 6, 7, 15, 45, 55, 80], 2: [2, 5, 10, 27, 335], 3: [3, 21, 28, 32, 35], 4: [4, 39]}

我想把这本字典作为字典导入我的Jupyter笔记本。我可以导入它,但它是字符串。

'{1: [1, 6, 7, 15, 45, 55, 80], 2: [2, 5, 10, 27, 335], 3: [3, 21, 28, 32, 35], 4: [4, 39]}'

但我想把它当作字典。我做错了什么?几乎没有什么玩笑,他们两个都不起作用。

有一种方法建议使用

d = {}
with open("jdictText.txt") as f:
for line in f:
(key, val) = line.split()
d[int(key)] = val

d
# But I got this error
ValueError                                Traceback (most recent call last)
<ipython-input-33-627c545e4457> in <module>
2 with open("jdictText.txt") as f:
3     for line in f:
----> 4        (key, val) = line.split()
5        d[int(key)] = val
6 
ValueError: too many values to unpack (expected 2)

另一种使用json的方法得到错误

import json
file_1 = open("jdictText.txt", 'r')
string = file_1.read()
d = json.loads(string)
d

JSONDecodeError                           Traceback (most recent call last)
<ipython-input-55-77dbdebba4e5> in <module>
2 file_1 = open("jdictText.txt", 'r')
3 string = file_1.read()
----> 4 d = json.loads(string)
5 d
JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

sf


file_1 = open("jdictText.txt", 'r')
string = file_1.read()
#Now removing { and }
s = string.replace("{" ,"")
finalstring = s.replace("}" , "")
#Splitting the string based on , we get key value pairs
list = finalstring.split(",")
dictionary ={}
for i in list:
#Get Key Value pairs separately to store in dictionary
keyvalue = i.split(":")
#Replacing the single quotes in the leading.
m= keyvalue[0].strip(''')
m = m.replace(""", "")
dictionary[m] = keyvalue[1].strip('"'')
print(dictionary)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-58-df2a2a3e5f37> in <module>
7 
8 print(string)
----> 9 print("Type: "+ type(string))
TypeError: can only concatenate str (not "type") to str
import json
file_1 = open("jdictText.txt", 'r')
string = file_1.read()
import ast
d = ast.literal_eval(string)
print(d)
type(d)

{'1': [1, 6, 7, 15, 45, 55, 80],
'2': [2, 5, 10, 27, 335],
'3': [3, 21, 28, 32, 35],
'4': [4, 39]}
dict

另一种方法是,您可以将其保存为Json文件,然后按如下方式导入。

import json
with open('jdicJSON.json') as f:
d = json.load(f)
print(d)    
type(d)

{'1': [1, 6, 7, 15, 45, 55, 80],
'2': [2, 5, 10, 27, 335],
'3': [3, 21, 28, 32, 35],
'4': [4, 39]}
dict

相关内容

  • 没有找到相关文章

最新更新