将列表数据转换为字典。

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

Convert list data into dictionary

问题

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

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

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

  1. (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):

  1. 'id': 'dungeons-and-raids',
  2. 'name': 'Dungeons & Raids',
  3. 'regionId': 'US',
  4. 'groups': [{
  5. 'content': {
  6. 'lines': [{
  7. 'icon': 'ability_toughness',
  8. 'name': 'Fortified',
  9. 'url': '/affix=10/fortified'
  10. }, {
  11. 'icon': 'spell_nature_cyclone',
  12. 'name': 'Storming',
  13. 'url': '/affix=124/storming'
  14. }, {
  15. 'icon': 'ability_ironmaidens_whirlofblood',
  16. 'name': 'Bursting',
  17. 'url': '/affix=11/bursting'
  18. }],
  19. 'icons': 'large'
  20. },
  21. 'id': 'mythicaffix',
  22. 'name': 'Mythic+ Affixes',
  23. },
  24. ...

And this is my complete Python 3.11 script:

  1. import re
  2. import json
  3. from urllib.request import Request, urlopen
  4. req = Request(
  5. "https://www.wowhead.com/today-in-wow", headers={"User-Agent": "Mozilla/5.0"}
  6. )
  7. html_page = urlopen(req).read().decode("utf-8")
  8. json_data = re.search(
  9. r"TodayInWow\(WH\.ge\('tiw-standalone'\), (.*), true\);", html_page
  10. )
  11. json_data = json.loads(json_data.group(1))
  12. data = {
  13. (d["id"], d["regionId"]): {dd["id"]: dd for dd in d["groups"]} for d in json_data
  14. }
  15. for affixline, affixp in enumerate(data[("dungeons-and-raids",
  16. "US")]["mythicaffix"]['content']['lines']):
  17. affixurl = affixp['url']
  18. affixname = affixp['name']
  19. affixid = affixline

This gives me the error:

  1. 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:

  1. import re
  2. import json
  3. from urllib.request import Request, urlopen
  4. req = Request(
  5. "https://www.wowhead.com/today-in-wow", headers={"User-Agent": "Mozilla/5.0"}
  6. )
  7. html_page = urlopen(req).read().decode("utf-8")
  8. json_data = re.search(
  9. r"TodayInWow\(WH\.ge\('tiw-standalone'\), (.*), true\);", html_page
  10. )
  11. json_data = json.loads(json_data.group(1))
  12. data = {
  13. (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
  14. }
  15. for affixline, affixp in enumerate(data[("dungeons-and-raids", "US")]["mythicaffix"]['content']['lines']):
  16. affixurl = affixp['url']
  17. affixname = affixp['name']
  18. print(affixurl, affixname)

Prints:

  1. /affix=10/fortified Fortified
  2. /affix=124/storming Storming
  3. /affix=11/bursting Bursting
英文:

Add a check if the returned group from the server is not null:

  1. import re
  2. import json
  3. from urllib.request import Request, urlopen
  4. req = Request(
  5. "https://www.wowhead.com/today-in-wow", headers={"User-Agent": "Mozilla/5.0"}
  6. )
  7. html_page = urlopen(req).read().decode("utf-8")
  8. json_data = re.search(
  9. r"TodayInWow\(WH\.ge\('tiw-standalone'\), (.*), true\);", html_page
  10. )
  11. json_data = json.loads(json_data.group(1))
  12. data = {
  13. (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
  14. }
  15. for affixline, affixp in enumerate(data[("dungeons-and-raids", "US")]["mythicaffix"]['content']['lines']):
  16. affixurl = affixp['url']
  17. affixname = affixp['name']
  18. print(affixurl, affixname)

Prints:

  1. /affix=10/fortified Fortified
  2. /affix=124/storming Storming
  3. /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:

确定