Section #8: Nested Dictionaries


Written by Ngoc Nguyen and Kavel Rao


In this section, you'll learn how to work with JSON structures and handle nested dictionaries. The dataset used in this problem contains three layers of nesting, similar to the Infinite Homework assignment, which will help you practice navigating through complex data structures.

Network

In this problem, you'll analyze a social network dataset stored in a JSON file.

Your Data

You have a dataset in JSON format that contains information about people and their friends. Each person has a list of their friends, and for each friend, we store how many years they've been friends. Each person's data is in social network structured something like this


{
    "network": {
        "Kavel": {
            "friends": [
                {
                "name": "Clinton",
                "years_friends": 6
                },
                {
                "name": "Diego",
                "years_friends": 2
                }
            ]
        },
        "Clinton": {
            "friends": [
                {
                "name": "Kavel",
                "years_friends": 6
                },
                {
                "name": "Anita",
                "years_friends": 4
                }
            ]
        }
    }
}
                   
    
            

Your actual dataset is much larger - go check it out in the file named data.json!

Task 1: Find Missing Friends

Given a dictionary from a JSON representation of a social network, your first task is to find and print the names of the friends who are mentioned but are missing from the network. Our code should avoid printing out names twice.

                
                def find_missing_friends(input_dict):


                
            
For example, using the small JSON dataset above,

The program should return the list of the names of these "missing" friends, which in this case would be

['Diego', 'Anita']

Run the provided doctest to make sure your code is working.

Task 2: Calculate Total Friendship Years

Given the dictionary from a JSON representation of a social network and a person's name, we want to write a function to calculate the total number of years a given person has been friends with their friends.

            
            def calculate_total_years(input_dict, name):


            
        

Using the small example friend network from above, asking for Clinton's total years of friendship will print

            Clinton has a total of 10 years of friendship.
            

When we ask for name that is not in the network like "Langston", the program should print

            Langston is not in the network.