Dictionaries – The Data Structure that Makes your Life Easier

Dictionaries are like, dictionaries. You can look things up in them. Given a key, you can look up a value. The best way to understand them is by example.

  • Step 1: See how a phone book could be implemented.
  • Lesson:
    • You can create an empty dictionary by my_dict = {}
    • You create a dictionary with elements like my_dict = {‘key1’: value1, ‘key2’: value2}
    • To look up a value by a key, e.g. ‘Rune’: my_dict[‘Rune’]
    • Adding new values to a key can be done by: my_dict[‘New key’] = value
  • Step 2: Try to look up a non-existing key, say, phone_book[‘Test’], in the above example.
  • Step 3: It is easy to iterate over a dictionary in Python.
  • Lesson: You can iterate over the keys in a dictionary with a for-loop: for key in dict:.
  • Step 4: Another way to think of dictionaries is like an archive, where you can store anything in each entry.
  • Lesson: Dictionaries are flexible and can be used for most data handling.
  • Step 5: Let’s try to count the occurrences of each word in a file.
  • Lesson: Dictionaries can easily be used to various things, like counting frequencies of words in a text.

Leave a Reply

%d bloggers like this: