简体   繁体   English

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

[英]How to import a multi-value dictionary in text file into python as a dictionary and what could go wrong. Need answer

I'm new to programming.我是编程新手。

I have a text file with a dictionary.我有一个带有字典的文本文件。

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

I want to import this dictionary into my Jupyter notebook as a dictionary.我想将这本字典作为字典导入到我的 Jupyter 笔记本中。 I was able to import it but it came as a string.我能够导入它,但它是一个字符串。

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

But I want it as a dictionary.但我想要它作为一本字典。 What I'm doing wrong?我做错了什么? There were few sujestion and didn't work either of them.有很少的sujestion,并没有工作他们中的任何一个。

One method sugest this一种方法建议这个

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)

The other method with json got the error使用 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

Other method is You can save it as a Json file and import it as follows.另一种方法是您可以将其另存为 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


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM