简体   繁体   English

将文件中的行添加为字典以列出Python

[英]Add lines from file as dictionary to list Python

Im trying to import a file which contains lines like this: 我正在尝试导入包含以下内容的文件:

 { "dictitem" : 1, "anotherdictitem" : 2 }

I want to import them in to a list of dictionaries like this: 我想将它们导入这样的词典列表中:

[{ "dictitem" : "henry", "anotherdictitem" : 2 },{ "dictitem" : "peter", "anotherdictitem" : 4 },{ "dictitem" : "anna", "anotherdictitem" : 6 }]

I tried this: tweetlist = open("sample.out").readlines() 我试过了: tweetlist = open("sample.out").readlines()

But then they get appended as a string. 但是随后它们被附加为字符串。 Does anyone have an idea? 有人有主意吗? Thanks! 谢谢!

You need to decode each line using json . 您需要使用json解码每一行。 Example: 例:

import json

list = []
with open("data.txt", 'r') as file:
    for line in file:
        dict = json.loads(line)
        list.append(dict)

print(list)

You can use the AST library's literal_eval function on each line by using a list comprehension like this: 您可以通过使用如下列表理解在每行上使用AST库的literal_eval函数:

import ast
tweetlist = [ast.literal_eval(x) for x in open("sample.out").readlines()]

ast.literal_eval is a safer version of the eval function that doesn't execute functions. ast.literal_eval是不执行功能的eval函数的安全版本。

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

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