如何用另一个字典的结果填充嵌套的字典

时间:2019-04-04 22:09:46

标签: python loops dictionary nested

我想使用另一个具有相同键的字典的结果来填充嵌套字典。需要有100个嵌套字典,例如下面的数字必须为0到99。

                retrieved_articles = [
            {
                "title": results["articles"]["results"][0]["title"],
                "date": results["articles"]["results"][0]["date"],
                "authors": results["articles"]["results"][0]["authors"],
                "body": results["articles"]["results"][0]["body"],
                "url": results["articles"]["results"][0]["url"],
                "accessed": date_accessed,
            },
            {
                "title": results["articles"]["results"][1]["title"],
                "date": results["articles"]["results"][1]["date"],
                "authors": results["articles"]["results"][1]["authors"],
                "body": results["articles"]["results"][1]["body"],
                "url": results["articles"]["results"][1]["url"],
                "accessed": date_accessed,
            },
                            {
                "title": results["articles"]["results"][...]["title"],
                "date": results["articles"]["results"][...]["date"],
                "authors": results["articles"]["results"][...]["authors"],
                "body": results["articles"]["results"][...]["body"],
                "url": results["articles"]["results"][...]["url"],
                "accessed": date_accessed,
            },
            {
                "title": results["articles"]["results"][99]["title"],
                "date": results["articles"]["results"][99]["date"],
                "authors": results["articles"]["results"][99]["authors"],
                "body": results["articles"]["results"][99]["body"],
                "url": results["articles"]["results"][99]["url"],
                "accessed": date_accessed,
            },

            ]

1 个答案:

答案 0 :(得分:1)

主要解决方案是在循环中创建字典并将其放入列表中。

retrieved_articles = []
for i in range(100):
    dictionary = {
                "title": results["articles"]["results"][i]["title"],
                "date": results["articles"]["results"][i]["date"],
                "authors": results["articles"]["results"][i]["authors"],
                "body": results["articles"]["results"][i]["body"],
                "url": results["articles"]["results"][i]["url"],
                "accessed": date_accessed,
            }
    retrieved_articles.append(dictionary)