0

I am using Python to query an api containing country information found at https://restcountries.com/v3.1/all.

Using the Python script below I am able to iterate over all the objects and extract the name and the country code.

Python Script

import requests
import json

api_url = 'https://restcountries.com/v3.1/all'

response = requests.get(api_url)

json_list = response.json()

for list_item in json_list:
    name = list_item["name"]["common"]
    country_code = list_item["cca2"]
    print(name)

The above works fine for what I need so far, however I also need to extract the currency code for the country and the complication is that the value I need is actually the name of the array eg. "USD": {"name": "United States dollar","symbol": "$"} here I would like to be able to extract "USD".

Example JSON

[
  {
    "name": {
      "common": "United States",
      "official": "United States of America",
      "nativeName": {
        "eng": {
          "official": "United States of America",
          "common": "United States"
        }
      }
    },
    "cca2": "US",
    "currencies": {
      "USD": {
        "name": "United States dollar",
        "symbol": "$"
      }
    },
    "region": "Americas",
    "subregion": "North America"
  }
]

Any help is greatly appreciated

1
  • You seem to have been able to extract the country code from the "cca2" key. Perhaps you could try to extract the dict from the "currencies" key. Commented Mar 5, 2022 at 17:28

1 Answer 1

1

In this case it might be helpful to use the .keys method on the sub dict currencies.

The issue with this is that for some list_items there is no 'currencies' key in which case there is no name to extract. Also in some cases there are more than one!

for list_item in json_list:
    name = list_item["name"]["common"]
    currency_keys = list(list_item.get('currencies', {}).keys())
    print(name)
    print(currency_keys)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.