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 maintain the insertion order.
  • The other programming language equivalents of a Python dictionary include maps of C++ Standard Library and the associative arrays of the Perl.

Key

Value

 USA

 Washington D.C.

 UK

 London

 Japan

 Tokyo

 France

 Paris

  • The dictionary implementation in Python is provided through the class dict.
  • The keys present in a Python dictionary are unique. There will not be any duplicate keys in a Python dictionary. The collection of key space in a Python dictionary is a set i.e., no two keys are same in a set.
  • The keys of a Python dictionary should be of immutable types.
  • A string literal, a numeric value can all be stored as a key in a Python dictionary. A Python tuple as well can be stored as a key in a Python dictionary for the reason being a string, a numeric value, a tuple are all immutable types.
  • However, a python list cannot be stored as a key in a Python dictionary, as a list is a mutable object.

Construction of a Python Dictionary:

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 of the Python Dictionary class:

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 available for a Python Dictionary object:

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 2024 © pythontic.com