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


Dictionary in Python is a dat type also known as map. You may be already familiar with them, if using Associative Arrays in PHP or Hash-tables 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 indexed by 1 and so on) you can use string indexes. Each element of a map is accessed (or, indexed) by an unique key, and so they are known as key-value pairs. Dictionaries are not sequences, hence maintains no left-to-right order.

Dictionaries are not sequences, hence maintains no left-to-right order.

Operations

You can create a map by the declaration: var_name = {key:value}

Code after “>>>” in following examples means: you need to type the code in Python command line. Any line not beginning with “>>>” indicates an output.

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

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

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

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

Alternately, you can declare an empty map, and insert key-value pairs later. Unlike Lists, you can perform out-of-bound assignments:

Code:
>>> D = {}

>>> D['name'] = 'Bob' # Create keys by assignment

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

>>> D['age'] = 40

>>> D
{'age': 40, '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'}}
About these ads

ReMo at Mozilla Reps, open-source enthusiast.

Tagged with: , , , , , , , ,
Posted in Beginning Python, Tutorials
5 comments on “Python Tutorial: Dictionaries (Key-value pair Maps) Basics
  1. Jonathan says:

    Very helpful! Thanks!

  2. susmitha says:

    This is very useful to the all students.please give me the python dictionaries

  3. Shafiul Azam says:

    Reblogged this on Shafiul Azam's Weblog and commented:

    Well-formatting some of my old posts! :)

  4. [...] terminal in UbuntuConvert multiple image files to single PDF (Batch convert image to PDF) in UbuntuPython Tutorial: Dictionaries (Key-value pair Maps) BasicsPostgreSQL with PHP in Ubuntu: Step-by-Step How To!Install Windows 7 From Pendrive: Make bootable [...]

  5. Glenn says:

    new to python… the nesting section REALLY helped. Thanks!

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

To keep the Web Open
Web docs by developers, for developers on MDN Work <span>for</span> Mozilla
Firefox OS
Thanks for visiting my blog!
  • 479,144 hits from Aug, 2009
Follow

Get every new post delivered to your Inbox.