Python Guided Project 1: Most Common Apps by Genre

Hi Guys,

I need help to understand this code in the display_table function provided in the solutions to most popular app by genre.

‘’'def display_table(dataset, index):
table = freq_table(dataset, index)
table_display =
for key in table:
key_val_as_tuple = (table[key], key)

    table_sorted = sorted(table_display, reverse = True)
    for entry in table_sorted:
    print(entry[1], ':', entry[0])'''

I do not understand this line of code: key_val_as_tuple = (table[key], key). It seems to me like key was selected twice but in different ways and I was expecting (table.items, key) type of selection to convert the dictionary to a list where the values comes first and the keys come second. Please explain. Here is the link:

Hey @nnyeka212!

I think it would be helpful to break this down into steps, starting with the loop:

for key in table:
    key_val_as_tuple = (table[key], key)

What you’re doing here is looping over each key in the frequency dictionary you just created using the freq_table function. For each key, you’re grabbing the value of the key using table[key] as well as the key itself and assigning it to a tuple. You then assign that tuple to a list so you can sort it.

So, for example, let’s take a look at this simple dictionary:

example_dict = {'App_X': 100}

We loop over the key:

key_val_as_tuple = (example_dict['App_X'], 'App_X') returns (100,'App_X')

… then append the result to the table_display list. The result looks like this:

[(100, 'App_X')]

This is why, in the table_sorted portion of the code, you’re indexing the second value first — the name of the key is found at index [1] of each tuple in the list.

Hey @dustindq!

Thanks for the explanation!