![](/img/trans.png)
[英]how to use nested dictionary in python which return user defined variable
[英]How to use variable as a nested dictionary item name?
我的腳本通過以下方式從嵌套字典中獲取數據:
wx = json.load(urllib2.urlopen('https://api.darksky.net/forecast/blabla.json'))
wd = {}
if 'hourly' in wx:
for item in wx['hourly']:
wd['d1'] = str(wx['hourly']['data'][1]['temperature'])
wd['d2'] = str(wx['hourly']['data'][2]['temperature'])
wd['d3'] = str(wx['hourly']['data'][3]['temperature'])
wd['d4'] = str(wx['hourly']['data'][4]['temperature'])
# ...and 20 more...
print wd['d1'] + '° ' + wd['d2'] + '° ' # and more...
我想減少此代碼的大小,並創建類似循環的內容。 但是我不能混合使用字符串和變量。 有沒有簡單的方法可以做到這一點?
for item in range(24):
wd["d{0}".format(item)] = str(wx['hourly']['data']['{item}']['temperature'])
更新 :
多虧了Jean-FrançoisFabre ,它只需要寫[item]
而不是['{item}']
。
保留原始代碼:
wx = json.load(urllib2.urlopen('https://api.darksky.net/forecast/blabla.json'))
wd = {}
if 'hourly' in wx:
for item in wx['hourly']:
wd['d'+str(i)] = str(wx['hourly']['data'][i]['temperature']) for i in range(1,25) #1st change
print '° '.join([wd['d'+str(i)] for i in range(1,25)]) #2nd change
然后你走了!
~~~~
一點解釋:
在#1st change
,我動態更新了值。 wd['d'+str(i)]
是wd
中鍵為'd' + str(i)
。 哦, ['data'][i]
['data'][1]
在第一個循環上基本上是['data'][1]
。
在#2nd change
,我做了一點工作,以所需的格式輸出所需的所有項目。 [wd['d'+str(i)] for i in range(1,25)]
生成[wd['d1'], wd['d2'], wd['d3'], ...]
為一個列表; 然后我用'° '
join()
編輯列表,這是您想要的分隔符。
希望我能幫上忙!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.