如何将变量用作嵌套字典项名称?

时间:2017-05-13 15:51:44

标签: python json python-2.x

我的脚本以这种方式从嵌套字典中获取数据:

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çois Fabre,只需要写[item]而不是['{item}']

1 个答案:

答案 0 :(得分:0)

保留原始代码:

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]

#2nd change中,我按照你想要的格式做了一个小单行输出你想要的所有项目。 [wd['d'+str(i)] for i in range(1,25)]生成[wd['d1'], wd['d2'], wd['d3'], ...]作为列表;然后我join()使用'° '编辑了列表,这是您想要的分隔符。

希望我帮忙!