Previous | Next


List is great when it come to group values into a structure and refer to each value by number. There is another useful data type built into Python called dictionary. The Python dictionary lets you organize your data for speedy lookup by associating your data with names or keys, not numbers.

 Dictionary = {'key1' : 'value1', 'key2': 'value2', ...}

The main operations on a dictionary are storing a value with some key and extracting the value given the key.

An empty dictionary:

The empty dictionary is written with a pair of curly curly brackets which containing nothing.
>>> phonebook = {}

Create and assign data into a dictionary:

Data should be written within the curly brackets with the structure of key : value
>>> phonebook = {
  'James' : '800-2138',
  'Sandy' : '810-3320',
  'Kelly' : '920-6390',
  'Tommy' : '638-1876'
  }
>>> phonebook
{'Kelly': '920-6390', 'James': '800-2138', 'Sandy': '810-3320', 'Tommy': '638-1876'}

To get length of a dictionary:

Use len() to get the length of a dictionary.
>>> len(phonebook)
4

Get the value associated with the key in a dictionary:

Returns the value associated with the key.
>>> phonebook['Sandy']
'810-3320'

Update the value associated with the key in a dictionary:

Associates the new value with the key.
>>> phonebook['Sandy'] = '812-2828'
>>> phonebook['Sandy']
'812-2828'

Delete the value associated with the key in a dictionary:

Delete the item with key.
>>> del phonebook['Sandy']
>>> phonebook
{'Kelly': '920-6390', 'James': '800-2138', 'Tommy': '638-1876'}

To check whether a key can be found in a dictionary:

Checks whether there is an item in dictionary that has the key.
>>> 'Sandy' in phonebook
False
>>> 'James' in phonebook
True
>>>

Previous | Next