Creation and use of dictionaries in Python

--Originally published at Quirino´s Projects

dictionaryA very useful data type in python are dictionaries, these could be understand as a list, but each element its a key with its respective value e.g.

We can have a list that holds every word in the english alphabet, but if we wanted to create a program that holds the number of times a letter appears in a string, creating a variable for each letter would be that practical, so a dictionary would be useful

alphabet = {“A”:0,”B”:0,”C”:0,”D”:0…}

Now we have a dictionary that holds a numerical value for each letter, the sintaxis of the dictionary is the following

{} The curly braces contain the dictionary

: The colon separates the key from the value of the key

“A” This is the key, it holds the value next to it

0 Its the value of the key

If we would like to add elements to our dictionary, we simply assign a value to a key is if it was already there

alphabet[“E”] = 5

A useful function when you are working with dictionaries is dictionary.keys(),this function returns the keys in a dictionary as a list, so we could check if a key is in the list before doing something with it

To get more info about dictionaries check:

https://www.tutorialspoint.com/python/python_dictionary.htm