Python Dictionary (With Examples)
Python Dictionary
Dictionary is an ordered set of a key-value pair of items. They work like associative arrays or hashes and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).
Example:
Output:
Accessing Dictionary Values
Dictionaries values can be accessed by using the square braces, i.e. [ ] along with the key name to obtain the value. This is multiple item declaration procedures used to declare keys along with their values in Python's dictionary.
Example:
Output:
Update Dictionary
Programmers can update or modify the existing dictionary by simply adding a new entry or a key-value pair or by deleting an item or entry.
Example:
Output:
Deleting Python
Dictionary Elements del statement is used for performing deletion operations. An item can be deleted from a dictionary using the key only.
Example:
Output:
Deleting full dictionary:
Example:
Output:
len(dict) Method
Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.
Example:
Output:
str(dict) Method
This method returns string formation of the value.
Example:
Output:
clear() Method
Removes all the elements from the dictionary.
Example:
Output:
copy() Method
Returns a copy of the dictionary.
Example:
Output:
get() Method
Returns the value of the specified key.
Example:
Output:
items() Method
Returns a list containing the tuple for each key-value pair.
Example:
Output:
keys() Method
Returns a list containing the dictionary's keys.
Example:
Output:
pop() Method
Removes the element with the specified key.
Example:
Output:
popitem() Method
Removes the last inserted key-value pair.
Example:
Output:
update() Method
Updates the dictionary with the specified key-value pairs.
Example:
Output:
values() Method
Returns a list of all the values in the dictionary.