Python - Data Type Dictionaries

Introduction

Python dictionaries are mappings.

Mappings are collections of other objects and store objects by key.

Mappings map keys to associated values.

Dictionaries are mutable, they may be changed in place and can grow and shrink on demand.

Operations

When written as literals, dictionaries are coded in curly braces and consist of a series of "key: value" pairs.

As an example, consider the following three-item dictionary with keys "food," "quantity," and "color," perhaps the details of a hypothetical menu item?:

Demo

D = {'food': 'Test', 'quantity': 4, 'color': 'pink'} 
print( D )

Result

We can index this dictionary by key to fetch and change the keys' associated values.

The dictionary index operation uses the same syntax as sequences.

Demo

D = {'food': 'Test', 'quantity': 4, 'color': 'pink'} 
print( D['food'] )              # Fetch value of key 'food' 
# from  ww  w .  j  ava  2 s  . c om
D['quantity'] += 1     # Add 1 to 'quantity' value 
print( D )

Result

The following code starts with an empty dictionary and fills it out one key at a time.

Demo

D = {} 
D['name'] = 'Jack'      # Create keys by assignment 
D['job']  = 'dev' 
D['age']  = 40 # w w w .j av a  2 s . co m

print( D )
print( print(D['name']) )

Result

Here, we're using dictionary keys as field names in a record that describes someone.

Related Topics