Solution 1

def tuple_count(a_tuple):
    result_dict = {}
    for item in a_tuple:
        result_dict.setdefault(item, 0)
        result_dict[item] += 1
    return result_dict

Solution 2

def tuple_count(a_tuple):
    result_dict = {}
    for item in a_tuple:
        if item not in result_dict.keys():
            result_dict[item] = 0
        result_dict[item] += 1
    return result_dict

Tuple Count

Complete the function tuple_count so that it receives a_tuple and returns a dictionary with a key of each item in the tuple and a value of the count of how many occurrences it has.

tuple_count(('a', 'b', 'a', 'b', 'b', 'c', 'd')) == {
    'b': 3,
    'd': 1,
    'a': 2,
    'c': 1
}

Test Cases

test tuple count with values - Run Test

def test_tuple_count_with_values():
    assert tuple_count(('a', 'a', 'b', 'b', 'b', 'c', 'd')) == {'b': 3, 'd': 1, 'a': 2, 'c': 1}

test tuple count empty - Run Test

def test_tuple_count_empty():
    assert tuple_count(tuple()) == {}
def tuple_count(a_tuple): pass