如何在变量中获取python词典的第一项值

时间:2017-08-21 13:21:02

标签: python dictionary show

程序

import pyowm
import pandas as pd

OWM=pyowm.OWM('ccb59666571a5e0bfe146f92ddf8e24f')
observation = OWM.weather_at_coords(19.997454,73.7898)
w = observation.get_weather()

temperature = w.get_temperature('celsius')

print(temperature)
for k,v in temperature.items()
  temp1=v[0]

输出

  

{'temp':22.47,'temp_max':22.47,'temp_min':22.47,'temp_kf':无}

从这个输出中我只想获得任何变量中第一项的值以供进一步使用。即22.47

它给了我这个错误信息:

  

“float'对象不是可订阅的python”

1 个答案:

答案 0 :(得分:0)

认为您正在寻找的是能够单独打印temptemp_max等等。

您这样做的方法是引用要打印的元素的索引。

# Lists
listName.index(0) # This would give the very first item in the list.
listName.index(len(listName) - 1) # This would give you the very last item in the list.

# Dictionaries (the one you're using for temperature)
dictionaryName['indexName'] # This would give you the item under indexName.
temperature['temp_max'] # This would give you the item under temp_max!

词典以与现实生活相同的方式工作。当你查找一个我们知道为索引的单词时,它会给我们一些信息。在python的情况下,我们指定字典,然后将索引放入方括号中。

# For the different values in the temperature dictionary...
temperature['temp'] #This is the value of 'temp' in dictionary temperature
temperature['temp_max'] #This is the value of 'temp_max' in dictionary temperature
temperature['temp_min'] #This is the value of 'temp_min' in dictionary temperature
temperature['temp_kf'] #This is the value of 'temp_kf' in dictionary temperature

然后单独打印出来,你将使用与打印变量相同的方法!

A dirty big page of documentation可能有所帮助! :d