Python Dictionary

Python Dictionary is an unordered collection of data values. Python Dictionary is used to store data values like a mapping pair. To make Python Dictionary optimized Key-value is provided. A dictionary is a collection that is changeable and it does not allow duplicates. Python Dictionary keys are case sensitive, different cases of Key and same name but they will be treated distinctly..

Creating Dictionary:

For Python Dictionary we place elements inside the curly braces { } and separated them by a comma. Python Dictionary holds a pair of values, one is the Key and the other is the corresponding pair element being its value written as Key: Value. Where Values can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable.

#Creating a Dictionary with Integer Keys 
Dict = {1: 'Python', 2: 'Programming'} 
print("a dictionary containing Integer Keys: ") 
print(Dict) 
  

Accessing values in Dictionary:

To access Python dictionary elements, the same square brackets with the key to obtain its value can be used.

#accessvalue

dict1 = {'Name': 'Alice', 'Age': 25, 'Country': 'UK'}

print ("dict1['Name']: ", dict1['Name'])
print ("dict1['Age']: ", dict1['Age'])

There is another way to access data in the dictionary is using the get ( ) method. By using this method, if the key is not found it returns None.

#accessvalue

dict = {'Name': 'Alice', 'Age': 25, 'Country': 'UK'}

print ("dict['Name']: ", dict['Name'])
print ("dict.get['Country']: ", dict['Country'])
print ("dict['city']", dict['city'])
print ("dict.get['city']", dict['city'])

Updating Dictionary Element:

By adding a new entry or a key-value pair, a dictionary can be updated. We can modify an existing entry, or delete an existing entry. The example given below can explain it to you.

#updating element

dict = {'Name': 'Alice', 'Age': 25, 'Country': 'UK'}

print ("dict['Name']: ", dict['Name'])
print ("dict['Country']: ", dict['Country'])
dict['Age'] = 26; #updating value
dict['City'] = London #adding new value
print ("dict['Age']: "  dict['Age'])
print ("dict['City']: " dict['City'])

Deleteing Dictionary Elements:

We can either clear the entire contents or remove individual dictionary elements of a dictionary. And also entire dictionary can be deleted in a single operation. The del statement is used to explicitly remove an entire dictionary.

dict = {'Name': 'Alice', 'Age': 25, 'Country': 'UK'}

del dict['Name']; #remove entry with key 'Name'
print ("dict= ", dict)
dict.clear();     #remove all entries in dict
print ("dict= ", dict)
del dict ;        #delete entire dictionary

Built-in Dictionary Methods:

Given below are the Built-in dictionary Methods,

MethodsDescription
update([other])This method updates the dictionary with the key/value pairs
from others, overwriting existing keys.
setdefault(key[,d])This method returns the corresponding value if the key is in the dictionary.
If not, inserts the key with a value of d and returns d (defaults to None).
get(key[,d])This method returns the value of the key. If the key does not exist,
returns d (defaults to None).
keys()This method returns a new object of the dictionary’s keys.
values()This method returns a new object of the dictionary’s values
pop(key[,d])This method removes the item with the key and returns its value or d
if the key is not found. If d is not provided and
the key is not found, it raises KeyError.
items()This method returns a new object of the dictionary’s
items in (key, value) format.
fromkeys(seq[, v])This method returns a new dictionary with keys from seq and
a value equal to v (defaults to None).
copy()This method returns a shallow copy of the dictionary.
clear()This method removes all items from the dictionary.
popitem()This method removes and returns an arbitrary item (key, value).
Raises KeyError if the dictionary is empty.

Built-in Dictionary Functions:

Given below are the Built-in dictionary Functions,

FunctionsDescription
any()Return True if any key of the dictionary is true.
If the dictionary is empty, return False.
all()Return True if all keys of the dictionary
are True (or if the dictionary is empty).
sorted()Return a new sorted list of keys in the dictionary.
cmp()Compares items of two dictionaries.
(Not available in Python 3)
len()Return the length (the number of items)
in the dictionary.