Using for loop in dictionary

def freq_table(dataset, index):
    table = {}
    total = 0
    for row in dataset:
        total += 1
        value = row[index]
        if value in table:
            table[value] += 1
            table[value] = 1
    table_percentages = {}
    for key in table:
        percentage = (table[key] / total) * 100
        table_percentages[key] = percentage 
    return table_percentages

Part 2 of the self-guided project to build the frequency table

Why does the author use “for key in table” instead of “for value in table”? I believe that this is due to my weak understanding of dictionaries so I would really appreciate guidance on the for loop and dictionary interactions. Thanks in advance!!!

Go through the below article may be it will help you.
Click Here

1 Like

As you know Dictionary is a set of (key , value) i.e. tablename {(key1, value1), (key2, value2),…}
For example dictionary named table: table[key1] = value1, table[key2] = value2,…

for key in table:
percentage = (table[key] / total) * 100
table_percentages[key] = percentage

“key” is variable name which could be anything
but here author takes the key part of dictionary to calculate the value i.e. table[key] for dictionary

  1. loop into table and iterate on “key” part of tablename “table”
  2. calculate percentage of current value which is table[key] and store into variable “percentage”
  3. Store key and its value into new dictionary named “table_percentages” (table_percentages[key] = percentage
    Hope it will help you
1 Like

Thanks for your insights into this topic, from what I can interpret here the table[key] stores the same value as table[value]??? And that the author technically can just use table[value] to calculate the percentage instead???

No, You cannot use table[value] to get value.
table[key] itself is the “value” .

for example:
table = {‘Orange’ : 1, ‘Apple’ : 4, ‘Banana’ : 0}
keys are [‘Orange’, ‘Apple’, ‘Banana’ ]
values are [1,4,0]

To get the value assigned to ‘Orange’ : table[‘Orange’]

table[‘Orange’] will return 1
table[‘Apple’] = 4
table[‘Banana’] = 0

when you know the key of dictionary, you can use table[key] to get “value” paired to that particular key.
In self-guided project,
we are calculating the percentage of “table” and storing data into new dictionary “table_percentages”

  1. for loop will take key from table
  2. table[key] will give its value, we will perform (table[key] / total) * 100 to calculate percentage
  3. we are assigning value (which is now “percentage”) at table_percentages[key] for “key”
    i.e. table_percentages = {key1: percentage1, key2: percentage2,…}