【问题标题】:Python; what does myLink = data["items"][0]["link"] do?Python; myLink = data["items"][0]["link"] 是做什么的?
【发布时间】:2018-08-19 13:02:35
【问题描述】:

myLink = data["items"][0]["link"] 在下面的代码 sn-p 中做了什么?我明白它说;如果我的 json 数据结构有键“items”,那么 [0]["link"] 部分是做什么的?

response = requests.get(resUrl)
data = response.json()

if data.has_key("items"):
    myLink = data["items"][0]["link"]
else:
    myLink = "no link found"

【问题讨论】:

  • 在列表的第 0 个索引处查找存储在“items”键上的字典,并获取存储在该字典的“link”键上的值。您应该能够打印 json 响应并遵循逻辑。
  • items键是一个数组,[0]获取第一个索引然后寻找link并返回。
  • 如果有的话,它会从存储的列表的第 0 个索引中获取链接。

标签: python json


【解决方案1】:
data = {'items':[{'link':'xxx'}, {'link':'yyy'}, {'link':'zzz'}]}

上面的dict()对象有一个dict()对象的内部数组作为值或键'items'.

要获得这个值,data["items"] 有效,解析数组中的元素[0]['link'] 有效。

["items"] get the value of 'items' key # O/P [{'link':'xxx'}, {'link':'yyy'}, {'link':'zzz'}]
["items"][0] first index of the array # O/P {'link':'xxx'}
["items"][0]['link'] key of the first index #O/P 'xxx'

我要感谢您提出的基本问题的勇气,许多人犹豫不决并在未来不及格。

干杯!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-08
    • 2010-12-20
    • 1970-01-01
    • 1970-01-01
    • 2011-05-04
    • 1970-01-01
    • 2015-12-06
    相关资源
    最近更新 更多