【发布时间】:2018-06-12 14:07:59
【问题描述】:
假设我有一个文件名列表files,其中包含 json 格式的数据。为了接收列表中的数据,每个文件都有一个条目,我使用列表推导:
>>> import json
>>> data = [json.load(open(file)) for file in files]
现在我想知道,是否有办法将文件名file 附加到 json 数据中,就好像它看起来像这样:
{
'Some': ['data', 'that', 'has', 'already', 'been', 'there'],
'Filename': 'filename'
}
就我而言,json.load() 返回一个dict,所以我尝试了类似于this question 的方法。这对我来说不起作用,因为files 包含字符串而不是字典。
编辑
为了澄清,如果dict.update() 没有返回None,这可能会起作用:
>>> data = [dict([('filename',file)]).update(json.load(open(file))) for file in files]
【问题讨论】:
-
你能在文件变量中显示你的值吗?
-
不是真的重复,但How to merge two dictionaries in a single expression?回答了您的问题。
标签: python json dictionary list-comprehension