Reputation: 334
I am attempting to create a dictionary by looping through a weather JSON file.
I want the key to be date and the value to be temperature from the nested "hours" in the JSON.
combined_temperature_hour = {date, temperature}
As I loop through the JSON file I can get the individual items but I can't figure out how to grab the two values and put them together in a (key, value) pair.
combined_temperature_hour = {}
for d in days:
for hours in d["hours"]:
hourly = hours.get('datetimeEpoch')
dia_y_hora = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(hourly))
complete_date.append(dia_y_hora)
h_temp = hours.get('temp')
hourly_temperature.append(h_temp)
#combined
combined = {complete_date, hourly_temperature}
print(combined)
JSON
"days":[
{
"datetime":"2021-01-01",
"datetimeEpoch":1609484400,
"tempmax":36.9,
"tempmin":32.4,
"temp":34.7,
"hours":[
{
"datetime":"00:00:00",
"datetimeEpoch":1609484400,
"temp":32.9,
},
{
"datetime":"01:00:00",
"datetimeEpoch":1609488000,
"temp":33.2,
},
{
"datetime":"02:00:00",
"datetimeEpoch":1609491600,
"temp":33.2,
}
]
}
This is what I would like the dictionary to look like after the loop
combined_temperature_hour = {`2021-01-24 05:00:00`: '25.1', `2021-01-24 06:00:00`: '26.2'}
I have tried grabbing the list for temperature and hour and combining into a dictionary them after the loop but I noticed that I am missing values and they are probably incorrect pairs.
Upvotes: 0
Views: 745
Reputation: 331
Read your json as a dictionary first into a variable a
(I changed some of the mismatching brackets in your json)
a = {"days":[
{
"datetime":"2021-01-01",
"datetimeEpoch":1609484400,
"tempmax":36.9,
"tempmin":32.4,
"temp":34.7,
"hours":[
{
"datetime":"00:00:00",
"datetimeEpoch":1609484400,
"temp":32.9,
},
{
"datetime":"01:00:00",
"datetimeEpoch":1609488000,
"temp":33.2,
},
{
"datetime":"02:00:00",
"datetimeEpoch":1609491600,
"temp":33.2,
}
]
}
]
}
Then you can have the expected output from the following code:
combined_temperature_hour = {}
for date in a['days']:
for hour in date['hours']:
combined_temperature_hour[date['datetime']+' '+hour['datetime']] = hour['temp']
Upvotes: 1