Dictionary: a brief guide to dictionaries (part 1)

Dictionary in Python

To create a dictionary in Python is easy. You can define one with this code:

my_dict = {}

To add something to my_dict, you can code like this:

my_dict["First key"] = "1st value"

Now, if you check what is inside my_dict, you will get this:

print(my_dict)

>>> {'First key': '1st value'}

As you can see a dictionary is made of a key and a value.

You can obtain the same result with this one line:

my_dict = {'First key': '1st value'}

Let’s say we got some other keys and values:

my_dict = {
         'First key': '1st value',
         'Second key' : '2nd value'
}

The different keys and values are separated by commas. The syntax is just like the javascript objects, btw.

Iterate through a dictionary in Python

Python has a great syntax to iterate through objects like lists and dictionaries.

To print all the keys in the my_dict dictionary, you go like this:

for k in mydict:
    print(k)

# the output will be
# First key
# Second key

To get the values:

for k in mydict:
    print(mydict[k])

# the output will be
# 1st value
# 2nd value

Delete a key

To delete a key, you do this:

del my_dict["First value"]

 

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.