【问题标题】:Nested dicts in pythonpython中的嵌套字典
【发布时间】:2016-01-08 09:18:03
【问题描述】:

我遇到了一个非常令人沮丧的问题。 我想从维基百科中获取所有类别和子类别、子类别等,并将其放入一个巨大的嵌套字典中。

我的问题是,例如,如果我找到顶级类别(类别:全部),我可以使用找到的子类别再次迭代循环,但我无法让它们嵌套在我的 dict 中。

有没有人可以提供一些帮助或查看错误。?

提前致谢,

import requests  # http://docs.python-requests.org/en/latest/
import json
from bs4 import BeautifulSoup

category = 'Categorie:Alles'

def wiki_api_request(category):
    url = ('http://nl.wikipedia.org/w/api.php?format=json&action=query&list=categorymembers&cmtitle=%s&cmlimit=500')%category
    return url

category_dict = {}

def crawl(category_name, _dict):
    url = wiki_api_request(category_name)

    _url = requests.get(url)


    extract = _url.json()

    category_amount = 0
    if 'query' in extract:
        category_list_json = extract['query']['categorymembers']
        _dict[category_name] = {category['title'] for category in category_list_json}

        for category in category_list_json:
            if 'Categorie:' in category['title']:
                crawl(category['title'], _dict[category_name] ** <-This gives an error**)
                break

crawl(category, category_dict)
print category_dict

错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-40-b8027c8281eb> in <module>()
     29                 break
     30 
---> 31 crawl(category, category_dict)
     32 print category_dict

<ipython-input-40-b8027c8281eb> in crawl(category_name, _dict)
     26         for category in category_list_json:
     27             if 'Categorie:' in category['title']:
---> 28                 crawl(category['title'], _dict[category_name])
     29                 break
     30 

<ipython-input-40-b8027c8281eb> in crawl(category_name, _dict)
     22     if 'query' in extract:
     23         category_list_json = extract['query']['categorymembers']
---> 24         _dict[category_name] = {category['title'] for category in category_list_json}
     25 
     26         for category in category_list_json:

TypeError: 'set' object does not support item assignment

【问题讨论】:

  • 什么错误?请编辑你的问题。
  • 不使用为什么还要导入bs4.BeautifulSoup
  • 那是为了稍后的分配
  • 请描述获取的url数据的json结构
  • 正如您的错误消息所述,错误是您在源中指定的位置上方 5 行。

标签: python json dictionary nested


【解决方案1】:

{category['title'] for category in category_list_json} 是集合推导,而不是字典推导。所以分配给_dict 的结果将是set

您可能想要一个将空字典作为值作为理解结果的字典,所以这样做

{category['title']:{} for category in category_list_json}

或更明确地

{category['title']:dict() for category in category_list_json}

【讨论】:

  • 是的,赞成。根据显示的错误TypeError: 'set' object does not support item assignment
猜你喜欢
  • 2018-05-31
  • 2011-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-17
  • 2023-01-23
  • 1970-01-01
相关资源
最近更新 更多