Home > Blockchain >  Populate Python dictionary with value in nested dictionary
Populate Python dictionary with value in nested dictionary

Time:10-10

I am using the AccuWeather RESTFul API to get the current weather conditions in the top 50 cities. One object of the JSON response looks like this:

{'Key': '28143', 'LocalizedName': 'Dhaka', 'EnglishName': 'Dhaka', 'Country': {'ID': 'BD', 'LocalizedName': 'Bangladesh', 'EnglishName': 'Bangladesh'}, 'TimeZone': {'Code': 'BDT', 'Name': 'Asia/Dhaka', 'GmtOffset': 6.0, 'IsDaylightSaving': False, 'NextOffsetChange': None}, 'GeoPosition': {'Latitude': 23.7098, 'Longitude': 90.40711, 'Elevation': {'Metric': {'Value': 5.0, 'Unit': 'm', 'UnitType': 5}, 'Imperial': {'Value': 16.0, 'Unit': 'ft', 'UnitType': 0}}}, 'LocalObservationDateTime': '2021-10-09T13:11:00 06:00', 'EpochTime': 1633763460, 'WeatherText': 'Mostly cloudy', 'WeatherIcon': 6, 'HasPrecipitation': False, 'PrecipitationType': None, 'IsDayTime': True, 'Temperature': {'Metric': {'Value': 32.2, 'Unit': 'C', 'UnitType': 17}, 'Imperial': {'Value': 90.0, 'Unit': 'F', 'UnitType': 18}}, 'MobileLink': 'http://www.accuweather.com/en/bd/dhaka/28143/current-weather/28143?lang=en-us', 'Link': 'http://www.accuweather.com/en/bd/dhaka/28143/current-weather/28143?lang=en-us'}

Now I want to populate a dictionary with 1) "EnglishName", 2) "WeatherText", and 3) "Temperature (Celsius)".

I do manage to get a key-value pair with "EnglishName" and "WeatherText" as below:

weatherResponse = result.json()
mydictionary = dict()

for p in weatherResponse:
    print(p["EnglishName"])
    print(p["LocalObservationDateTime"])
    print(p["WeatherText"])
    temp_C = list(p["Temperature"]["Metric"].values())[0]
    print(f"Temperature in Celsius: {temp_C}")
    print("--------")
    mydictionary[p["EnglishName"]] = p["WeatherText"]

How can I assign the "temp_C" value of each key to the dictionary as well? I tried the append function but that does not work.

Any help is appreciated!

CodePudding user response:

I want to populate a dictionary with 1) "EnglishName", 2) "WeatherText", and 3) "Temperature (Celsius)". See below

data = [{
  'Key': '28143',
  'LocalizedName': 'Dhaka',
  'EnglishName': 'Dhaka',
  'Country': {
    'ID': 'BD',
    'LocalizedName': 'Bangladesh',
    'EnglishName': 'Bangladesh'
  },
  'TimeZone': {
    'Code': 'BDT',
    'Name': 'Asia/Dhaka',
    'GmtOffset': 6.0,
    'IsDaylightSaving': False,
    'NextOffsetChange': None
  },
  'GeoPosition': {
    'Latitude': 23.7098,
    'Longitude': 90.40711,
    'Elevation': {
      'Metric': {
        'Value': 5.0,
        'Unit': 'm',
        'UnitType': 5
      },
      'Imperial': {
        'Value': 16.0,
        'Unit': 'ft',
        'UnitType': 0
      }
    }
  },
  'LocalObservationDateTime': '2021-10-09T13:11:00 06:00',
  'EpochTime': 1633763460,
  'WeatherText': 'Mostly cloudy',
  'WeatherIcon': 6,
  'HasPrecipitation': False,
  'PrecipitationType': None,
  'IsDayTime': True,
  'Temperature': {
    'Metric': {
      'Value': 32.2,
      'Unit': 'C',
      'UnitType': 17
    },
    'Imperial': {
      'Value': 90.0,
      'Unit': 'F',
      'UnitType': 18
    }
  },
  'MobileLink': 'http://www.accuweather.com/en/bd/dhaka/28143/current-weather/28143?lang=en-us',
  'Link': 'http://www.accuweather.com/en/bd/dhaka/28143/current-weather/28143?lang=en-us'
}]

filtered_data = [{'EnglishName':e.get('EnglishName','NA'),'WeatherText':e.get('WeatherText','NA'),'temp_C':e.get('Temperature').get('Metric').get('Value')} for e in data]
print(filtered_data)

output

[{'EnglishName': 'Dhaka', 'WeatherText': 'Mostly cloudy', 'temp_C': 32.2}]

CodePudding user response:

Instead of adding only one value p["WeatherText"] to your dictionary you can add multiple through use of tuples, like (a,b). Please see the below line.

mydictionary[p["EnglishName"]] = (p["WeatherText"], p["Temperature"]["Metric"]["Value"])

This above line you can use to assign to your dictionary key multiple values, sample output from this:

{'Dhaka': ('Mostly cloudy', 32.2)}

You can read tuples just like lists

mydictionary["Dhaka"][0]          # This for getting the text 
mydictionary["Dhaka"][1]          # This for getting the value

Also tuples may look similar to lists but in this case it is recommended to use tuples because lists should store same data type values and tuples can store multiple datatype values.

  • Related