'How do I optimize/make a cleaner code to retrieve values in sub_keys of nested dictionary, case insensitive

I am fairly new to programming and I need to run a code to search through a nested dictionary and retrieve every value for each sub_key.

I was able to make it run, but I would like to know if there is a better solution? Any suggestions on how to improve my code, making it shorter/cleaner and "error-proof"? Anything will be greatly appreciated.

The user will input the province, which is the first level key. From there I have to assemble a string with all the values for the sub_keys.

This is my nested dictionary:

canadian_provinces_dict = {
    'Ontario': {"capital": "Toronto", "largest": "Toronto", "population": 14223942},
    'Quebec': {"capital": "Quebec City", "largest": "Montreal", "population": 8501833},
    'Nova Scotia': {"capital": "Halifax", "largest": "Halifax", "population": 969383},
    'New Brunswick': {"capital": "Fredericton", "largest": "Moncton", "population": 775610},
    'Manitoba': {"capital": "Winnipeg", "largest": "Winnipeg", "population": 1342153},
    'British Columbia': {"capital": "Victoria", "largest": "Vancouver", "population": 5000879},
    'Prince Edward Island': {"capital": "Charlottetown", "largest": "Charlottetown", "population": 154331},
    'Saskatchewan': {"capital": "Regina", "largest": "Saskatoon", "population": 1132505},
    'Alberta': {"capital": "Edmonton", "largest": "Calgary", "population": 4262635},
    'Newfoundland and Labrador': {"capital": "St. John's", "largest": "St. John's", "population": 510550},
    'Northwest Territories': {"capital": "Yellowknife", "largest": "Yellowknife", "population": 41070},
    'Yukon': {"capital": "Whitehorse", "largest": "Whitehorse", "population": 40232},
    'Nunavut': {"capital": "Iqaluit", "largest": "Iqaluit", "population": 36858},
}

This is my function:

def get_province_description(province_name, this_dict):
    """
    This function will retrieve the values for the indexed sub_keys of the given province,
    representing the individual information for this province.
    :param province_name: Inputted province, to be used as a first-level key.
    :param this_dict: Given dictionary to be accessed.
    :return: Returns a string description for the given province_name
    """
    if province_name.title() in this_dict:
        if this_dict[province_name.title()]["capital"] == this_dict[province_name.title()]["largest"]:
            print("%s has a population of %i whose capital and largest city is %s" % (province_name.title(), this_dict[province_name.title()]["population"], this_dict[province_name.title()]["capital"]))
        elif this_dict[province_name.title()]["capital"] != this_dict[province_name.title()]["largest"]:
            print("%s has a population of %i whose capital is %s and largest city is %s" % (province_name.title(), this_dict[province_name.title()]["population"], this_dict[province_name.title()]["capital"], this_dict[province_name.title()]["largest"],))
        else:
            return None


Solution 1:[1]

Welcome to the community! I'm not quite sure what you're asking here exactly but if you're just looking for general advice, a few things come to mind. I do recommend modifying your question to ask a specific question as questions deemed to be open ended are prone to being closed.

My suggestions:

  1. Break out the check for largest city into a separate check.

  2. Use an 'f-string'. Perhaps it is just preference, but I feel that it looks cleaner.

https://realpython.com/python-f-strings/

This is how I would consider writing it:

output = f"{province_name.title()} has a population of {this_dict[province_name.title()]['population']} whose capital "
if this_dict[province_name.title()]["capital"] == this_dict[province_name.title()]["largest"]:
    output += f"and largest city is {this_dict[province_name.title()]['capital']}"
elif this_dict[province_name.title()]["capital"] != this_dict[province_name.title()]["largest"]:
    output += f"is {this_dict[province_name.title()]['capital']} and largest city is {this_dict[province_name.title()]['largest']}"
else:
    output = None

return output

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ryan Lutz