growthandknowledge
growthandknowledge

Reputation: 69

Pull a value from a dictionary

I'm getting an error whenever I try to pull the temp value. The error is: TypeError: string indices must be integers

This is my code:

for item in data['main']:
    tempday=item['temp']

This is the API I am pulling from:

{
"coord": {},
"weather": [],
"base": "stations",
"main": {
    "temp": 53.2,
    "pressure": 1021,
    "humidity": 71,
    "temp_min": 44.6,
    "temp_max": 57.2
},
"visibility": 16093,
}

I want to get the "temp" value of 53.2. What am I doing wrong with my code?

Upvotes: 0

Views: 862

Answers (3)

Muhammad Usman
Muhammad Usman

Reputation: 10936

tempday=item['temp'] returns the key names. you need to iterate over to get values for all items. data['main']

for item in data['main']:
     data['main'][item]

Output

53.2 
1021
71
44.6
57.2

To get only one item

tempday=data['main']['temp']

Upvotes: -1

Nils Werner
Nils Werner

Reputation: 36765

Your code assumes that the content of data['main'] is an iterable of dicts and is trying to get temp of all of those dicts.

Since it is just another single dict, you can drop the for loop and simply use

tempday=item['main']['temp']

Upvotes: 3

parsethis
parsethis

Reputation: 8078

to explain the error, in general a dict iterates of its keys, the keys in this case are just strings. So doing:

for k in some_dict:
  # k is a string
  # some_dict[k] return the value of k in the dict

Upvotes: 0

Related Questions