如何在python中阅读字典?

时间:2016-06-17 11:17:48

标签: python json file dictionary

我有一个名为“input.txt”的文件。在这个文本文件中存储了很多字典。我必须遍历这些词典。如何读取文件?每当我使用open(),file.read()读取文件时,它会将整个文本转换为字符串类型。如何将此文件作为词典集合阅读?

input.txt的内容:

{"label":18,"words":["realclearpolitics","-","election","2016","-","2016","republican","presidential","nomination","polls","year","state"]}

5 个答案:

答案 0 :(得分:4)

字符串中缺少结束列表括号。您可以使用this之类的代码 - 使用python的现有json模块:

import json

x = '{"label":18,"words":["realclearpolitics","-","election","2016","-","2016","republican","presidential","nomination","polls","year","state"]}'
j = json.loads(x)
print(j)

答案 1 :(得分:2)

如果一行的内容是格式正确的dict,你可以使用eval在python中执行字符串

line = {"label":18,"words":["realclearpolitics","-","election","2016","-","2016","republican","presidential","nomination","polls","year","state"]}
dictionary = eval(line)
print(dictionary)

因此,如果输入中只有一行,则可以使用

dictionary = eval(open("input.txt").read())

或者如果每行有一个字典

with open('input.txt', 'r') as f:
    for line in f:
         dictionary = eval(line)

答案 2 :(得分:1)

使用json模块的方法将文件中每行加载的str转换为dict

import json

with open('input.txt','r') as f:
    for line in f.readlines():
        line_as_dict = json.loads(line)
        # process here the dict

答案 3 :(得分:1)

您可以尝试以下

import ast
import json

def readfile():
    f = open(path_to_file, 'r')
    content = f.read()
    data = ast.literal_eval(content)
    print(json.loads(data))

如果输入不是有效的Python数据类型,则ast.literal_eval会引发异常,因此如果不是,则不会执行代码。因此,从文件中读取的内容也会得到验证

<强>输出:

{'label': 18,
 'words': ['realclearpolitics',
  '-',
  'election',
  '2016',
  '-',
  '2016',
  'republican',
  'presidential',
  'nomination',
  'polls',
  'year',
  'state']}

答案 4 :(得分:0)

您的JSON不正确,您错过了关闭数组,但更正后的JSON低于:

{
    "label": 18,
    "words": ["realclearpolitics", "-", "election", "2016", "-", "2016", "republican", "presidential", "nomination", "polls", "year", "state"]
}

您可以使用json内置函数load来读取JSON文件:

import json
with open(r'path\of\your\file') as data_file:
    jsonData = json.load(data_file)
    print jsonData # it will print whole JSON data
    print jsonData['words'] # it will print value of the key `word`