Python Dictionary Methods with Example

Python Dictionary:

Python Dictionary is a data structure in which we store values as a pair of keys and values. Each key is separated from its value by a colon(:) and consecutive items are separated by a comma(,). The entire items in a dictionary are enclosed in curly brackets{}. It has the following syntax:

dictionary_name={key_1: value1, key_2: value2, key_3: value3}

Creating a Dictionary in Python:

The syntax to create an empty dictionary is given below:

dictionary_variable=[]

Example:

Doc=[]
print(Doc)

Output:
[]

The syntax to create a dictionary with a key-value pair is given below:

dictionary_variable={key_1: value1, key_2: value2, key_3: value3}

Example:

Doc={'Roll_no':71874, 'Name':'Rohit', 'Stream':'CSE'}
print(Doc)

Output:
{‘Roll_no’: 71874, ‘Name’: ‘Rohit’, ‘Stream’: ‘CSE’}

Python Dictionary Methods:

MethodsDescription
len(Dict)It returns the length of Dictionary.
str(Dict)It returns a string representation of the dictionary.
Dict.clear()It deletes all entries in the dictionary.
Dict.copy()It returns a shadow copy of the dictionary.
Dict.fromkeys(seq[,val])It creates a new directory with keys from seq and values set to val.
Dict.get(key)It returns the value for the key passed as argument.
Dict.has_key(key)It returns True, if the key is present in the dictionary and false otherwise.
Dict.items()It returns a list of tuples (key-value pair)
Dict.keys()It returns a list in the dictionary.
Dict.setdefault(key, value)It sets a default value for a key that is not present in the dictionary.
Dict1.update(Dict2)It adds the key-value pairs of Dict2 to the key-value pairs of Dict1
Dict.values()It returns a list of values in dictionary
Dict.iteritems()It is used to iterate through items in the dictionary.
in and not in It checks whether a given key is present in dictionary or not.