Python Dictionaries

Introduction to Dictionaries in Python

A Dictionary in Python Programming Language is a container for a set of key value pairs. The key value pairs stored in a Python Dictionary are not sorted or ordered based on any criteria.

 

The other programming language equivalents of a python dictionary include Maps, Associative Arrays.

 

Example of a Python Dictionary Object:

 

Key

Value

USA

Washington D.C.

UK

London

Japan

Tokyo

France

Paris

 

The keys in a Python dictionary are unique. There will not be any two duplicate keys in a Python dictionary. The collection of key space in the Python dictionary is a set i.e., no two keys are same in a set.

 

The keys of a Python Dictionary should be of mutable types.

 

A String, Number can be stored as a key in the Python Dictionary. A Python Tuple as well can be stored as a key in a Python Dictionary. The reason a String, Number or Tuple can be stored as a key in a Python Dictionary is they are all immutable types.

 

However a python list cannot be stored as a key in a Python Dictionary, because a list in Python is a mutable object.

 

 

 

Python Dictionary Construction

Using braces { }

 

Dictionary objects in python are crated by placing key-value pairs inside a pair of braces.

 

dict()

 

Creates an empty dictionary.

 

dict(keyword-argument-list)

 

Creates a python dictionary as specified in the keyword-argument-list.

 

dict(mapping)

 

Creates a python dictionary from a mapping object or from another dictionary.

 

dict(iterable)

 

Creates a python dictionary from an iterable object.

 

 

Methods on a Python Dictionary Object

Dict[dict_key_in]

 

Retrieves the value associated with dict_key_in parameter, otherwise called a dictionary lookup.

 

get(dict_key[,default_value])

 

Returns the value associated with a key in the python dictionary object.

 

del dict[dict_key_in]

 

Deletes a key-value pair as identified by the key.

 

Clear()

 

The clear method removes all the items from the dictionary.

 

Copy()

 

Returns a shallow copy of the python dictionary object.

 

get(dict_key[,default_value])

 

Returns the value associated with a key in the python dictionary object.

 

Popitem()

 

Removes an arbitrary item from a Python Dictionary object.

 

 

Built in Functions for Python Dictionary

len(dict_in)

 

Returns the number of items stored in a python dictionary object.

 

key in dict

 

Determines whether a given key is present in the python dictionary.

 

key not in dict

 

Determines whether a given key is not present in the python dictionary.

 


Copyright 2018 © pythontic.com