【问题标题】:How to initialize an a priori unknown number of list如何初始化一个先验未知数量的列表
【发布时间】: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


【解决方案1】:

你可以使用collections.defaultdict,像这样

from collections import defaultdict
d = defaultdict(list)
for x in data:
    d[x['author']].append(x)

每当找到不在字典中的作者时,都会创建一个新列表并将其用作值,并将当前项目附加到列表中。


你可以用普通的字典做同样的事情,像这样

d = {}
for x in data:
    d.setdefault(x['author'], []).append(x)

如果你想在从文件中读取作者时保持作者的顺序,那么你可以使用collections.OrderedDict,像这样

from collections import OrderedDict
d = OrderedDict
for x in data:
    d.setdefault(x['author'], []).append(x)

【讨论】:

    猜你喜欢
    • 2014-04-21
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    • 2012-11-24
    • 2012-07-09
    • 2023-03-14
    • 2011-01-14
    • 2017-10-31
    相关资源
    最近更新 更多