python-3.x 将列表数据转换为字典

0pizxfdo  于 2023-06-25  发布在  Python
关注(0)|答案(1)|浏览(100)

我从一个网站上提取了一个脚本的内容。现在,我想将接收到的数据列表转换为字典,以便于搜索。

json data(json_data)看起来像这样(部分):

'id': 'dungeons-and-raids',
    'name': 'Dungeons & Raids',
    'regionId': 'US',
    'groups': [{
        'content': {
            'lines': [{
                'icon': 'ability_toughness',
                'name': 'Fortified',
                'url': '/affix=10/fortified'
            }, {
                'icon': 'spell_nature_cyclone',
                'name': 'Storming',
                'url': '/affix=124/storming'
            }, {
                'icon': 'ability_ironmaidens_whirlofblood',
                'name': 'Bursting',
                'url': '/affix=11/bursting'
            }],
            'icons': 'large'
        },
        'id': 'mythicaffix',
        'name': 'Mythic+ Affixes',
    },
   ...

这是我完整的Python 3.11脚本:

import re
import json
from urllib.request import Request, urlopen

req = Request(
    "https://www.wowhead.com/today-in-wow", headers={"User-Agent": "Mozilla/5.0"}
)
html_page = urlopen(req).read().decode("utf-8")

json_data = re.search(
    r"TodayInWow\(WH\.ge\('tiw-standalone'\), (.*), true\);", html_page
)
json_data = json.loads(json_data.group(1))

data = {
    (d["id"], d["regionId"]): {dd["id"]: dd for dd in d["groups"]} for d in json_data
}

for affixline, affixp in enumerate(data[("dungeons-and-raids", 
"US")]["mythicaffix"]['content']['lines']):

    affixurl = affixp['url']
    affixname = affixp['name']
    affixid = affixline

这给了我error

TypeError: 'NoneType' object is not subscriptable

似乎dd["id"]返回“None”,但我不知道为什么。在这种情况下,怎样正确使用词典?

fhg3lkii

fhg3lkii1#

如果从服务器返回的组不是null,则添加检查:

import re
import json
from urllib.request import Request, urlopen

req = Request(
    "https://www.wowhead.com/today-in-wow", headers={"User-Agent": "Mozilla/5.0"}
)
html_page = urlopen(req).read().decode("utf-8")

json_data = re.search(
    r"TodayInWow\(WH\.ge\('tiw-standalone'\), (.*), true\);", html_page
)
json_data = json.loads(json_data.group(1))

data = {
    (d["id"], d["regionId"]): {dd["id"]: dd for dd in d["groups"] if dd} for d in json_data  # <-- add check if group is not null
}

for affixline, affixp in enumerate(data[("dungeons-and-raids", "US")]["mythicaffix"]['content']['lines']):
    affixurl = affixp['url']
    affixname = affixp['name']
    print(affixurl, affixname)

图纸:

/affix=10/fortified Fortified
/affix=124/storming Storming
/affix=11/bursting Bursting

相关问题