Dictionaries

A dictionary is a common data structure in Python. It is used to store unidirectional mappings from keys to values. For example, if we wanted to create a dictionary that stored a list of patient names and their corresponding room numbers, we could use the following code:

rooms = {
'Smith': '141-A',
'Davis': '142',
'Williams': '144',
'Johnson': '145-B'
}

Let's talk about the preceding code snippet in more detail:

  • The names in the rooms dictionary are referred to as keys. The keys in a dictionary must be unique. To access them, we can use the keys() function, rooms.keys().
  • The room numbers in the rooms dictionary are referred to as values. To access all of the values, we can use the values() function, rooms.values(). To access an individual value, we just supply the name of its key in square brackets. For example, rooms['Smith'] will return '141-A'. For this reason, we say that a dictionary maps keys to their values.
  • To access a nested list of tuples that contains each key along with its corresponding value, we can use the items() function, rooms.items().
  • Dictionaries don't have to just be strings; in fact, the values can be any data type/structure. The keys can be particular variables such as integers or strings. While the values are mutable, the keys are immutable.
  • Dictionaries have no intrinsic order, so indexing and slicing by number is not supported.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset