为什么Python首先告诉我我的对象是字典(它是什么),然后是列表?

时间:2017-09-08 06:56:33

标签: python-3.x dictionary

我正在尝试访问一个字典,它有很长的密钥,并从密钥中提取一些数据。我正在尝试查看数据,所以同时:

for k,v in line.items():
    if k == 'n':
        print('Label: ' + , v)
    if k == 'o':
        print(json_data.keys())

我想用它来帮助我确定键的长度,以便我可以指出字典。当我这样做时,Python告诉我

Traceback (most recent call last):
  File "C:\Users\spect\Desktop\gw2api\jsonapi.py", line 22, in <module>
    print(json_data.keys())
AttributeError: 'list' object has no attribute 'keys'

但真正令我困惑的是,当我试图剥离()或分割()字典时,我觉得我很困惑,而且它是一个字符串---来自API的信息--- Python告诉我

Traceback (most recent call last):
   File "C:\Users\spect\Desktop\gw2api\jsonapi.py", line 16, in <module>
     line.split()
AttributeError: 'dict' object has no attribute 'split'

API是JSON,所有信息都是Python中的多字典项目的字典,所以当Python制作它的字典时,它会分配一些非常长的密钥。

要回答你的问题,我只是在练习Python,使用游戏API。     #the常用的导入工具     import urllib.parse     导入请求     来自pprint import pprint

#game api address schema
main_api = 'https://api.guildwars2.com/v2/titles?'
url = main_api + urllib.parse.urlencode({'ids':'all'})

json_data = requests.get(url).json()

#I resolved to switch around my two blocks of code so that the portions I n eeded were accessible. it was scoping more or less.
for line in json_data:
    for k,v in line.items():
        if k == 'achievements':
            json_data2 = requests.get(url).json()
            #here i'm supposed to be grabbing the id from json_data in a     placeholder fashion but really using the number to get the id f rom json_data2, it isn't working. json_data data is coming back.
            iden = v
            sec_url = 'https://api.guildwars2.com/v2/achievements?ids='
            url = sec_url + urllib.parse.urlencode({'ids':'iden'})
            json_data2 = requests.get(url).json()
            print('Achievement: ', iden)
        if k == 'name':
            print('Title: ', v)
希望这会让它更清晰。 API发送回多个字典,python放在列表中。

1 个答案:

答案 0 :(得分:1)

您正在使用2个变量:json_data这是一个列表,line是一个词典。

根据您的修改:

API不返回多个字典,它以这种形式返回JSON:

[
  {
    "id": 1,
    "name": "Traveler",
    "achievement": 111,
    "achievements": [
      111
    ]
  },
  {
    "id": 2,
    "name": "Guild Warrior",
    "achievement": 112,
    "achievements": [
      112
    ]
  },
...
]

要迭代响应,您只需要将其解析为json(通过调用json.loads(),我猜这正是json() requests.get()方法的作用。然后你可以使用一个简单的for循环:

for title in json_data:
    print("Title: " + title["name"])
    print("Achievement: " + title["achievement"])