login

Python Dictionary

Introducing to Python dictionary

Python dictionary is a built-in type that defines one-to-one relationships between keys and values. Python dictionary is also known as hash table or associative array. The English dictionary book is a good example of Python dictionary where you can find the meaning of an English word from a specific word. You can access any value of a dictionary through a key therefore there is no duplicate key exist in the Python dictionary.

Defining Python dictionaries

Like a list, you can define an empty dictionary or initialize dictionary items as below:

# empty dictionary
empty_dict = {} 

# stock quote dictionary
stock_quote = {'AIG':'American International Group. Inc.',
        'CSCO':'Cisco Systems, Inc.',
         'GE':'General Electric Company'} 

First we create an empty dictionary which is using curly braces instead of square bracket like a Python list.

Second we create a stock quote dictionary which has three elements and assign it to a variable stock_quote. Each element is a key-value pair. For example 'AIG' is key and 'American International Group. Inc.' is value. You can get value by key but cannot get key by value. For example to company name by symbol 'GE' we use the following form:

stock_quote['GE'] #General Electric Company

Manipulating Python dictionary

You can add any new key-value pairs to a dictionary with the rule that the added key is unique inside the dictionary. If you assign a new value to an existing key the old value will wipe out. You can remove either single item in a dictionary or entire dictionary by using del keyword. Below example demonstrates the dictionary manipulation:

#!/usr/bin/python
def print_dict(dict):
    """ 
    print dictionary
    """ 
    for key,value in stock_quote.items():
        print(key + ':' + value) 
    

# stock quote dictionary
stock_quote = {'AIG':'American International Group. Inc.',
               'CSCO':'Cisco Systems, Inc.',
               'GE':'General Electric Company'} 

# changing existing value
stock_quote['AIG'] = 'What company is that?'
# add new item to the dictionary 
stock_quote['AFFY'] = 'Affymax, Inc.'

print_dict(stock_quote) #output dictionary content

#removing single item
del stock_quote['AIG']

print_dict(stock_quote)  #output dictionary content


stock_quote.clear() #removing all the items of dictionary
del stock_quote     # delete dictionary


These are built-in dictionary object methods:

Methods

Description

dict.copy( )

Returns a shallow copy of the dictionary

dict.has_key(k)

Returns true if key is a key in dict; otherwise, returns False, just like key in dict

dict.items( )

Returns a new list with all items (key/value pairs) in dict

dict.keys( )

Returns a new list with all keys in dict

dict.values( )

Returns a new list with all values in dict

dict.iteritems( )

Returns an iterator on all items (key/value pairs) in dict

dict.iterkeys( )

Returns an iterator on all keys in dict

dict.itervalues( )

Returns an iterator on all values in dict

dict.get(key[, x])

Returns dict[key] if key is a key in dict; otherwise, returns x (or None, if x is not given)

dict.clear( )

Removes all items from dict, leaving dict empty

dict.updictate(dict1)

For each key in dict1, sets dict[key] equal to dict1[key]

dict.setdictefault(key[, x])

Returns dict[key] if key is found in dict; otherwise, sets dict[key] equal to x and returns x

dict.pop(key[, x])

Removes and returns dict[key] if key is found in the dictionary dict; otherwise, returns x  or raises an exception if x is not given.

dict.popitem( )

Removes and return returns an arbitrary item (key/value pair)

Python dictionary key

Python dictionary allows more than just a string as key. In fact, any immutable and hashtable can be used as a key to a dictionary. An immutable object is an object that cannot be modified once it is created. Here is the table which includes data types that can be used as a dictionary key.

Data Type

Immutable?

Hashable?

Dictionary key?

int

Yes

Yes

Yes

float

Yes

Yes

Yes

boolean

Yes

Yes

Yes

complex

Yes

Yes

Yes

str

Yes

Yes

Yes

bytes

Yes

Yes

Yes

bytearray

No

No

No

list

No

No

No

tuple

Yes

Sometimes

Sometimes

set

No

No

No

frozenset

Yes

Yes

Yes

dictionary

No

No

No