【发布时间】:2016-04-11 19:37:39
【问题描述】:
我正在尝试用 python 重新构建一个 json 文件。 json 是一个 json 数组,其中每个元素都是一个字典。在这些字典中,一些对我很重要的键有很多重复值,所以我想将每个字典的所有其他键放在一个数组中,以获得相同的重要键值,创建一个具有不同结构的 json .
然后对于某个键的每个不同值,我想初始化一个数组。问题是这个键的不同值的数量是先验未知的。我想要的代码示例:
data = json.loads(originalJson)
# List of different authors for key ['author']
authors = []
for x in data:
if x['author'] not in authors:
authors.append(x['author'])
newData = []
for author in authors:
for x in data:
if x['author'] == author:
# And here is the code that initialize
# a different array for each author
P.S.:如果您知道重组 json 的更有效方法,请给我一个链接、示例或其他内容。你会注意到我对 python “非常初学者”。
编辑:输入和输出示例
originalJson = [{ke1 : value, key2 : value, key3 : value,...},{...},....]
wantedJson = [{key1 : valueX,[{key2 : value, ...},{key3 : value,...},...]},
{key1 : valueY, [...]},{key1 : valueZ,[...]}]
【问题讨论】:
-
请发布输入和预期匹配输出的示例。
-
为什么不使用以作者为关键字的new_data字典?
-
你的问题太模糊了。正如@brunodesthuilliers 所说,我们需要一些样本输入和输出。
标签: python arrays json list dictionary