将列表数据转换为字典。

huangapple go评论62阅读模式
英文:

Convert list data into dictionary

问题

这个错误是因为在以下这行代码中,dd["id"] 返回了 None

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

造成这个问题的原因可能是 JSON 数据中某些子项缺少 "id" 键。为了解决这个问题,你可以在访问 dd["id"] 之前添加一些检查,以确保键存在。例如,你可以使用 get 方法来访问键,如果键不存在,则返回一个默认值,如下所示:

(d["id"], d["regionId"]): {dd.get("id", "Unknown"): dd for dd in d["groups"]} for d in json_data

这将返回 "Unknown" 如果 "id" 键不存在。这样,即使 JSON 数据中某些子项缺少 "id" 键,你的代码也不会引发 TypeError 错误。

英文:

I have extracted the content of a script from a website. Now I want to transform the received data list to a dictionary to have an easier search.

The json data (json_data) looks like that (part of):

 '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',
    },
   ...

And this is my complete Python 3.11 script:

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

This gives me the error:

TypeError: 'NoneType' object is not subscriptable

It seems dd["id"] returns "None", but I don't know why. What is the correct way to use the dictionary in this case?

答案1

得分: 3

Add a check if the returned group from the server is not 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)

Prints:

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

Add a check if the returned group from the server is not 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)

Prints:

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

huangapple
  • 本文由 发表于 2023年6月15日 06:08:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76477888.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定