Dictionaries In Python

Hi. This page is on dictionaries in Python. A dictionary is an object which stores data. The two parts to a dictionary include a key and a value.


Some of the Python dictionary functions that are displayed here are used with an example of countries with their capitals.



The format for a dictionary is dictionary[key]. With the example, the key is the country and having dictionary[key] obtains the capital for the country.



in and not in Keywords

In if statements, the keywords in and not in can be used to determine if something is in a dictionary.



Adding To A Dictionary

Adding to a dictionary is quite simple. If I wanted to add the country of Germany with the capital of Berlin the dictionary[key] = value format would be used. In the example, I use places[‘Germany’] = ‘Berlin’.



Deleting From A Dictionary

The del keyword is for deleting elements in a dictionary. In the example below, I delete Belgium and Brussels from the list.



For Loop In A Dictionary

A for loop can be used to loop through elements in a dictionary. The variable is key and the dictionary is places in the example below.



Leave a Reply