Python Tutorial: Dictionaries (Key-value pair Maps) Basics


Dictionary in Python is a data-structure also known as map. Chances are you’re already familiar with them, if using Associative Arrays in PHP or Hashtables in C++ or Java. You may imagine a dictionary as an array, where instead of numerical indexes (the first element of array is indexed as 0, the second element is indexed by 1 and so on), you use string indexes. Each element of a map is accessed (or, indexed) by an unique “key”; so they are also known as key-value pairs. Dictionaries are not sequences, so the order in which elements are added to the dictionary doesn’t matter.

Example

Suppose, we want a data-structure to store information about a cooking recipe. For the recipe, we want to store which food (dish) we’re cooking, how many quantities it serve, and the color of the food being  prepared (don’t ask me why).

You can create a map using this syntax: variable_name = {key:value}

In the following examples, any text after “>>>” is actual code that you use in your Python scripts. You can also type this code in Python command line interpreter. Any line not beginning with “>>>” indicates an output of the previous code.

Code:
>>> D = {'food': 'pudding', 'quantity': 4, 'color': 'pink'}

>>> D['food'] # Fetch value of key 'food'
'pudding'

>>> D['quantity'] += 1 # Add 1 to 'quantity' value

>>> D
{'food': 'pudding', 'color': 'pink', 'quantity': 5}

Alternately, you can create an empty map, and insert key-value pairs later. Unlike Lists (arrays in Python), you can perform out-of-bound assignments:

Code:
>>> D = {}

>>> D['name'] = 'Bob' # Insert element on-the-fly

>>> D['job'] = 'dev'

>>> D['age'] = 4

>>> D
{'age': 4, 'job': 'dev', 'name': 'Bob'}

>>> print D['name']
Bob

Nesting

Like lists, nesting is also possible in maps. Consider the following code pattern:

Code:
>>> rec = {'name': {'first': 'Bob', 'last': 'Smith'},
                  'job': ['dev', 'mgr'],
                  'age': 40.5}

>>> rec['name'] # 'Name' is a nested dictionary
{'last': 'Smith', 'first': 'Bob'}

>>> rec['name']['last'] # Index the nested dictionary
'Smith'

>>> rec['job'] # 'Job' is a nested list
['dev', 'mgr']

>>> rec['job'][-1] # Index the nested list
'mgr'

>>> rec['job'].append('janitor') # Expand Bob's job description in-place

>>> rec
{'age': 40.5, 'job': ['dev', 'mgr', 'janitor'], 'name': {'last': 'Smith', 'first':
'Bob'}}
Advertisements

5 thoughts on “Python Tutorial: Dictionaries (Key-value pair Maps) Basics

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s