Итерация по JSON файлу в python 3 - PullRequest
0 голосов
/ 09 апреля 2020

В настоящее время я пытаюсь получить данные о строгости из файла json, который содержит даты и страны. Вот выдержка из того, как выглядит вывод json:

import pandas as pd
import json
from bs4 import BeautifulSoup

# load file
with open("Stringency April 8.txt") as file:
    stringency_data = json.load(file)

stringency_data["data"]

#this gives the output:

{'2020-01-02': {'ABW': {'confirmed': None,`
   'country_code': 'ABW',
   'date_value': '2020-01-02',
   'deaths': None,
   'stringency': 0,
   'stringency_actual': 0},
  'AFG': {'confirmed': 0,
   'country_code': 'AFG',
   'date_value': '2020-01-02',
   'deaths': 0,
   'stringency': 0,
   'stringency_actual': 0},
  'AGO': {'confirmed': None,
   'country_code': 'AGO',
   'date_value': '2020-01-02',
   'deaths': None,
   'stringency': 0,
   'stringency_actual': 0},
  'AUS': {'confirmed': 0,
   'country_code': 'AUS',
   'date_value': '2020-01-02',
   'deaths': 0,
   'stringency': 7.14,
   'stringency_actual': 7.14},
  'AUT': {'confirmed': 0,
   'country_code': 'AUT',
   'date_value': '2020-01-02',
   'deaths': 0,
   'stringency': 0,
   'stringency_actual': 0},.........

Вот мой код (пока я немного его сократил ради этого поста):

# create empty list for dates

date_index = []
[date_index.append(date) for date in stringency_data["data"]]



#creates empty lists for countries

Australia = []
Austria = []
...
US = []

# put these lists into a list
countries_lists = [Australia, Austria,...US]

# put country codes into a list
country_codes = ["AUS", "AUT",..."USA"]
# loop through countries

i = 0

for country, code in zip(countries_lists, country_codes):
    while i<=len(date_index):
        country.append(stringency_data["data"][date_index[i]][code]["stringency_actual"])
        i+=1

Когда я печатаю список «Австралия», я получаю все нужные значения. Но страна из Австрии и далее остается пустым списком.

Я получаю вывод - KeyError : "AUS". Это указывает на то, что код извлекает весь временной ряд, но только для первой страны (Австралия). Как я могу l oop это для каждого кода страны?

...