我使用字典,它本身就有很多字典。我需要引用其中一个元素,比如说,在其他字典中。这是其中的一小部分:
{
"success": true,
"start": 0,
"pagesize": "100",
"total_count": 7084,
"listinginfo": {
"3307294723760205578": {
"listingid": "3307294723760205578",
"price": 0,
"fee": 0,
"publisher_fee_app": 730,
"publisher_fee_percent": "0.100000001490116119",
"currencyid": 2006,
"asset": {
"currency": 0,
"appid": 730,
"contextid": "2",
"id": "20015271739",
"amount": "0",
}
},
"3306168823851241677": {
"listingid": "3306168823851241677",
"price": 177,
"fee": 25,
"publisher_fee_app": 730,
"publisher_fee_percent": "0.100000001490116119",
"currencyid": 2017,
"steam_fee": 8,
"publisher_fee": 17,
"converted_price": 23,
"converted_fee": 3,
"converted_currencyid": 2001,
"converted_steam_fee": 1,
"converted_publisher_fee": 2,
"converted_price_per_unit": 23,
"converted_fee_per_unit": 3,
"converted_steam_fee_per_unit": 1,
"converted_publisher_fee_per_unit": 2,
"asset": {
"currency": 0,
"appid": 730,
"contextid": "2",
"id": "19841538651",
"amount": "1",
}
},
}
我需要访问相应路径中的“listingid”和“id”元素['listinginfo']['3307294723760205578']['listingid']和['listinginfo']['3307294723760205578']['listingid']['资产 ']['id']。问题是字段'3307294723760205578'是动态的并且每次都在变化。是否有可能以某种方式“跳过”它并走得更远?类似['listinginfo'][key]['listingid'] 的东西。现在我正在像这样循环遍历元素(其中 steam_skin 是同一个字典):
for m in steam_skin:
for a in steam_skin:
for key in steam_keys[1:]:
m = steam_skin['listinginfo'][key]['listingid']
a = steam_skin['listinginfo'][key]['listingid']['asset']['id']
此代码失败并出现错误:
Traceback (most recent call last):
File "steam.py", line 153, in <module>
a = steam_skin['listinginfo'][key]['listingid']['asset']['id']
TypeError: string indices must be integers
我得到“m”的最上面一行是什么- 有效。字典显示我访问的所有元素都是字符串。另一个重要条件:我需要同时获得相同的'm'和'a',并在代码中进一步同时使用它们以形成一个url,这也是动态的。
问题是如何解决这个错误以及代码是否通常会按照我需要的方式工作。我的意思是,当内部循环通过变量'a'时,不是会改变,但'm'会保持不变吗?感谢您的帮助,我希望有一个解决方案。
使用dpath模块,可以搜索任意深度的嵌套键和值:
关键是您试图
steam_skin['listinginfo'][key]['listingid']像字典一样访问它,但它没有键,它只是一个字段。所以更换
a = steam_skin['listinginfo'][key]['listingid']['asset']['id']在
a = steam_skin['listinginfo'][key]['asset']['id']