Understanding Dictionary Syntax In Python

Inserting a new key-value pair to an empty dictionary using dictionary['key'] = value syntax can be pretty confusing. This article will help you understand this concept more clearly.

What is the cause of the confusion?

If the dictionary is empty, how can we do dictionary['key'] = value? You may think that in order to use a key in the syntax dictionary['key'] = value, it should exist in the dictionary. The error below shows us why you might think that:

>>> dictionary = {}
>>> dictionary['non_existent_key']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'non_existent_key'

If using a key that doesn’t exist causes an error, how can dictionary['key'] = value syntax work?

Let’s grasp it!

In order to understand how it works, we have to imagine the dictionary key to be working similar to a variable. In the case of a variable, we can just create a new one if it doesn’t exist. And if it exists the value in the variable is updated and if we are not assigning, the value in it will be returned.

variable = 1 # variable created
variable = 2 # variable updated
variable # value is returned

The same happens with an empty dictionary:

dictionary = {}

dictionary['key'] = 1 # key created
dictionary['key'] = 2 # key updated
dictionary['key'] # value is returned

Let’s use this code to reinforce the above case:

letters = ['A', 'B', 'B', 'B', 'A', 'C', 'D', 'D']

letter_count = {}


for letter in letters:
    if letter in letter_count:
        letter_count[letter] += 1
        # equivalent to letter_count[letter] = letter_count[letter] + 1
    else:
        letter_count[letter] = 1
        
print(letter_count)
{'A': 2, 'B': 3, 'C': 1, 'D': 2}

At first, we created a simple list called letters and our intention is to get the frequency of the letters in the list. And then, we declared an empty dictionary called letter_count to store the frequency of those letters. The code will loop through each letter in the list and it will check whether the dictionary already has a key with the same name as the current value of the for loop variable (iterator). And if a key exists, it will add 1 to the value of the dictionary key. Otherwise, if the key is not found, it will create a new key with the same name as the current value of the iterator.

I hope this has helped you understand how a dictionary can be updated even if it’s empty initially.

7 Likes

Thank you. The Dictionaries part of this course has been the most difficult so far!

1 Like