在 python 中使用可变字典键从嵌套 json 获取结果
Getting results from nested json with variable dict keys in python
我想从嵌套的 json 文件中提取 "date"、"account"、"extended_tweet" 和 "location",其中的可变字典键从 1 到 500 .
如何使用我的代码片段循环遍历 Python 3.8 中的所有 500 个指令?
我现在只得到第一个 dict 相同结果的 500 倍。
data = json.load(json_data)
json_data.close()
for i in list(range(0, 501)):
date = data['1']['created_at']
account = data['1']['user']['name']
extended_tweet = data['1']['retweeted_status']['extended_tweet']['full_text']
location = data['1']['user']['location']
print(date, account, extended_tweet, location)
试试这个:
for i in range(1, 501):
date = data[str(i)]['created_at']
account = data[str(i)]['user']['name']
extended_tweet = data[str(i)]['retweeted_status']['extended_tweet']['full_text']
location = data[str(i)]['user']['location']
print(date, account, extended_tweet, location)
您的代码中的错误:
- 您在范围内循环,但没有使用循环计数器来获取确切的密钥。您需要获取键
'1'
、'2'
、... for 循环,但每次都使用相同的 '1'
。
- 您需要使用
range(1, 501)
,而不是您正在执行 range(0, 501)
,这也会尝试获取 '0'
的密钥。
- 改进,不是错误:您不需要使用
list(range())
;相反,您可以直接使用 range()
进行循环。
我想从嵌套的 json 文件中提取 "date"、"account"、"extended_tweet" 和 "location",其中的可变字典键从 1 到 500 .
如何使用我的代码片段循环遍历 Python 3.8 中的所有 500 个指令?
我现在只得到第一个 dict 相同结果的 500 倍。
data = json.load(json_data)
json_data.close()
for i in list(range(0, 501)):
date = data['1']['created_at']
account = data['1']['user']['name']
extended_tweet = data['1']['retweeted_status']['extended_tweet']['full_text']
location = data['1']['user']['location']
print(date, account, extended_tweet, location)
试试这个:
for i in range(1, 501):
date = data[str(i)]['created_at']
account = data[str(i)]['user']['name']
extended_tweet = data[str(i)]['retweeted_status']['extended_tweet']['full_text']
location = data[str(i)]['user']['location']
print(date, account, extended_tweet, location)
您的代码中的错误:
- 您在范围内循环,但没有使用循环计数器来获取确切的密钥。您需要获取键
'1'
、'2'
、... for 循环,但每次都使用相同的'1'
。 - 您需要使用
range(1, 501)
,而不是您正在执行range(0, 501)
,这也会尝试获取'0'
的密钥。 - 改进,不是错误:您不需要使用
list(range())
;相反,您可以直接使用range()
进行循环。