Python Tutorial: Dictionaries (Key-value pair Maps) Basics
Dictionaries are also known as maps. In fact they are collection of objects, but unlike Lists, each individual value of a map is accessed by an unique key, and so they are known as key-value pairs.
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.
>>> 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:
>>> 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:
>>> 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'}}
Jonathan 4:41 pm on April 29, 2010 Permalink |
Very helpful! Thanks!
susmitha 2:34 pm on April 29, 2011 Permalink |
This is very useful to the all students.please give me the python dictionaries
Shafiul Azam 10:34 am on January 31, 2012 Permalink |
Reblogged this on Shafiul Azam's Weblog and commented:
Well-formatting some of my old posts!