Python Tutorial
Python - Introduction Python - Syntax Python - Variable Python - Number Python - Casting Python - String Python - Operators Python - Conditions Python - Loops Python - List Python - Tuple Python - Set Python - Dictionary Python - Function Python - Module Python - Date & Time Python - Input Output Python - Error & Exception Python - File Handling
Python OOP
OOP - Introduction OOP - Class Members OOP - Constructor Destructor OOP - Data Hiding OOP - Inheritance OOP - Overriding OOP - Overloading

Python Dictionary

In python dictionary is a collection which is unordered, changeable and indexed. Dictionaries are written with curly brackets and consists of key value pairs. The value can be accessed by unique key in the dictionary.

Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

Accessing Values in Dictionary

To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value.

Updating Dictionary

You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown in a simple example given below.

Delete Dictionary Elements

You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation.

To explicitly remove an entire dictionary, just use the del keyword:

Python Built-in dictionary Functions

Function Description
len(dict) Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.
str(dict) Produces a printable string representation of a dictionary
type(dict) Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type.

Python Built-in dictionary Methods

Method Description
dict.clear() Removes all elements of dictionary dict
dict.copy() Returns a shallow copy of dictionary dict
dict.fromkeys() Create a new dictionary with keys from seq and values set to value.
dict.get(key, default=None) For key key, returns value or default if key not in dictionary
dict.items() Returns a list of dict's (key, value) tuple pairs
dict.keys() Returns list of dictionary dict's keys
dict.setdefault(key, default = None) Similar to get(), but will set dict[key] = default if key is not already in dict
dict.update(dict2) Adds dictionary dict2's key-values pairs to dict
dict.values() Returns list of dictionary dict's values