Home > Enterprise >  How to access a specific dictionary value present inside a function in python
How to access a specific dictionary value present inside a function in python

Time:06-27

I want to take the key value of location_data['country'] and compare it with a string value(name of a country) outside the function.

import requests

def get_ip():
    response = requests.get(
      'https://api64.ipify.org?format=json').json()
    return response["ip"]


def get_location():
    ip_address = get_ip()
    response = requests.get(
      f'https://ipapi.co/{ip_address}/json/').json()
    location_data = {
      "ip": ip_address,
      "city": response.get("city"),
      "region": response.get("region"),
      "country": response.get("country_name")
    }
    return location_data

CodePudding user response:

Just compare it after you call the get_location function.

location_data = get_location()
if location_data.get('country') == 'country_string':
    pass

Try using get method when looking for a key's value in dict, otherwise, you might have a KeyError if the key doesn't exist.

CodePudding user response:

Wouldn't it be get_location()['country'] == 'string value' ?

CodePudding user response:

It seems that you may be unfamiliar with how return works.

Since you are returning the dictionary, you can store it in a variable and access it.

location_data = get_location()
if location_data['country'] == "whateverstring":
   #Do whatever here

Basically, you are storing what the function returns in a variable, which, in this case is the dictionary of the location data, which you can access outside of the function.

Ramintafromlt also provides a way of doing it, instead of storing what the function returns in a variable, you can just directly compare the value for that particular key.

  • Related