Python Dictionaries.

Hello all, before we dive into today's article. I would like to inform you that I have been attending a four week python bootcamp organised by Data Science East Africa and Lux Tech Academy.
So far I have learnt all the basics of python some of which I have been writing about here. Additionally, we have also been introduced to Flask and FAST API and this week we shall be handling data science.

Now back to today's article.

Dictionaries.

Dictionary in Python is an ordered collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized.

  • Creating a dictionary You can use the dict() function to create an empty dictionary in python.
# creating an empty dictionary
  dictionary = dict()
  print(dictionary)
  {}

The curly brackets represent an empty dictionary. To add an item to the dictionary we use the square brackets.

>>>dictionary['one'] = 'uno'

The above piece of code creates an item that maps from the key 'one' to the value 'uno'.
Printing the dictionary again gives a key-value pair with the key and value. {'one':'uno'}.
We can continue adding more items to the dictionary using the method demonstrated above.

>>> dictionary = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
   >>> print(dictionary)
   {'one': 'uno', 'three': 'tres', 'two': 'dos'}
  • Accessing the items in the dictionary. The order of items in a dictionary is not the same. You may get a different arrangement when you type the same items in the above demonstration example. The elements in a dictionary are not indexed meaning we can not access them via indices, instead we use keys as a 'substitute' for indices to access the values against it.
>>>print(dictionary['one'])
      'uno'

From above, we see that 'uno' is returned because we used it's key 'one' to access it.
To know the number of key-value pairs we use len() function.

>>>len(dictionary)
      3

The in operator can be used to tell whether something appears as a key in the dictionary.

>>>'one' in dictionary
    True
>>> 'uno' in dictionary
    False

To check whether something appear as a value, you can use the method values to return a list of values and them use the in operator to find it.

>>>values  = list(dictionary.values())
   >>> 'uno' in values
      True
  • Dictionaries as counters. Suppose we want to count the number of times a letter appears in a word, we can loop through and increment our counter every time the letter is found.
word = 'brontosaurus'
  d  = dict()
  for o in word:
      if o not in d:
         d[0] = 1
     else:
        d[0] = d[0] + 1
print(d)
# we get {'o':2}

This article is being updated.

14