solutions

Process nested dicts

Write a function analyze_age_in_dicts that receives a list of dictionaries, pulls the value associated with the key "age" from each dictionary, and returns a new dictionary with two keys:

  • 'avg_age': The average age of the input dict
  • 'dictionary_count': The number of elements processed
analyze_age_in_dicts([{
  "name": "Bob",
  "age": 22
  }, {
  "name": "Jane",
  "age": 26
}])

# {"avg_age" : 24.0, "dictionary_count" : 2}

Test Cases

test dict without age key - Run Test

def test_dict_without_age_key():
    original = [{
        "name": "Bob",
        "age": 22
    }, {
        "name": "Jane",
        "age": 26
    }, {
        "name": "Alice",
        "last_name": "Jones"  # WARNING! No age key.
    }]
    expected = {"avg_age": 24.0, "dictionary_count": 2}
    assert analyze_age_in_dicts(original) == expected

test process one dict - Run Test

def test_process_one_dict():
    original = [{
        "name": "Hermione",
        "age": 23
    }]
    expected = {"avg_age": 23.0, "dictionary_count": 1}
    assert analyze_age_in_dicts(original) == expected

test process two dicts - Run Test

def test_process_two_dicts():
    original = [{
        "name": "Bob",
        "age": 22
    }, {
        "name": "Jane",
        "age": 26
    }]
    expected = {"avg_age": 24.0, "dictionary_count": 2}
    assert analyze_age_in_dicts(original) == expected