首页 > 解决方案 > 如何将文本文件中的多值字典作为字典导入 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]}'

但我想要它作为字典。我做错了什么?很少有sujestion,也没有工作。

一种方法建议这样做

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)

科幻


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

标签: pythonarrayspython-3.xlistdictionary

解决方案


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



推荐阅读