Python Dictionary

Here, we have discussed about the python dictionary, how to create python dictionary, adding elements to a dictionary, accessing elements of....

In this articles we will discuss about the python dictionary, how to create python dictionary, adding elements to a dictionary, accessing elements of dictionary, removing elements of dictionary, python dictionary methods and built-in function in dictionary.

Python Dictionary

What is Python Dictionary?

In python, dictionary is an unordered collection of elements and these elements are stored in format or simply we can say that all the elements of the dictionary has the pairs. The python dictionaries are mutable which means that we can change it after its creation.

Creating Python Dictionary

We can create a python dictionary by simply writing the element within the Curly brackets and these elements are separated by the conmas (,). Each element of the dictionary has a key and a value corresponding to it which are expressed in a pair . A key should be an immutable and unique whereas a value can be mutable and of any data type.

# Python empty dictionary

dic = {}

# Python dictionary with integer keys

dic = {3: 'Cat', 2: 'Dog'}

# Python dictionary with mixed keys

dic = {'class': 'First', 3: [14, 9, 2]}

# by using dict()

dic = dict({1:'Cat', 2:'Dog'})

# from sequence having each item as a pair

dic = dict([(3,'Cat'), (2,'Dog')])

Adding elements to Python Dictionary

Python dictionaries are mutable which means that we can change it after its creation. We can add elements in the python dictionary in many ways. We can add value in the dictionary by using specified keys. We can update a value along with the key Dict= . And with the function we can update the existing elements of a dictionary. The existing value gets updated if the key is already present in the dictionary or otherwise a new is added in the given dictionary.

# Creating an empty Python Dictionary

Dic = {}   

print("Empty Dictionary: ")   

print(Dic)   

# Adding elements to Python dictionary one at a time   

Dic[1] = 'Python'  

Dic[2] = 'Programming Language'  

Dic[3] = 'Tutorials'  

print("\nPython Dictionary after adding 3 elements: ")   

print(Dic)   

# Adding set of values with a single Key   

# The value doesn't exist to dictionary 

Dic['value'] = 14, 9, 2  

print("\nPython Dictionary after adding 3 elements: ")   

print(Dic)   

# Updating existing Key's Value   

Dic[3] = 'Answersjet'

print("\nUpdated key value: ")   

print(Dic)    

Output

Empty Dictionary: 

{}

Python Dictionary after adding 3 elements:

{1: 'Python', 2: 'Programming Language', 3: 'Tutorials'}

Python Dictionary after adding 3 elements:

{1: 'Python', 2: 'Programming Language', 3: 'Tutorials', 'value': (14, 9, 2)}

Updated key value:

{1: 'Python', 2: 'Programming Language', 3: 'Answersjet', 'value': (14, 9, 2)}

Accessing elements to Python Dictionary

A python dictionary uses keys to access the elements as keys are unique. To access the elements of a dictionary we can use the key with the method or we also use key inside the square brackets . If we use the method and the key is not found then it returns whereas if we have used the square brackets and the key is not found then it returns .

# Accessing elements to Python Dictionary

dic = {'Name': 'Ekta', 'Age': 21}

# Output: Ekta

print(dic['Name'])

# Output: 26

print(dic.get('Age'))

# Trying to access keys which doesn't exist

# Output will be None

print(dic.get('Class'))

# Gets a KeyError

print(dic['Class'])

Output

Ekta

21

None

Traceback (most recent call last):

File "<string>", line 11, in <module>

KeyError: 'Class'

Removing elements to Python Dictionary

In python, we can remove the elements of a dictionary using many different methods which ar explained as follows;

Using del Keyword

By using the keyword, we can delete or remove the elements one by one as well as we can delete the entire dictionary.

dic = {

  "Name": "Deepak",

  "Class": "Seventh",

  "Roll no.": 69

}

del dic["Class"]

print(dic)

Output

{'Name': 'Deepak', 'Roll no.': 69}

The keyword can also delete the dictionary completely. In the following example, let's delete the full dictionary;

dic = {

  "Name": "Deepak",

  "Class": "Seventh",

  "Roll no.": 69

}

del dic

print(dic)

Output

Traceback (most recent call last):

  File "<string>", line 8, in <module>

NameError: name 'dic' is not defined

Using pop() method

The function is also used to remove a element from the dictionary. It removes the value which is associated with the given key and returns the value.

dic =	{

  "Name": "Deepak",

  "Class": "Seventh",

  "Roll no.": 69

}

dic.pop("Class")

print(dic)

Output

{'Name': 'Deepak', 'Roll no.': 69}

Using popitem() method

By using the function we can delete and return the arbitrary elements pair in the dictionary.

dic ={

  "Name": "Deepak",

  "Class": "Seventh",

  "Roll no.": 69

}

dic.popitem()

print(dic)

Output

{'Name': 'Deepak', 'Class': 'Seventh'}

Using clear() method

By using the method, we can remove or delete all the items of a dictionary at once.

dic =	{

  "Name": "Deepak",

  "Class": "Seventh",

  "Roll no.": 69

}

dic.clear()

print(dic)

Output

{}

Python Dictionary Methods

The following is the list of all python dictionary methods;

Method Description
values() To return a list of values of all objects in the dictionary.
pop() To remove elements with specified key from a dictionary.
clear() To remove all elements of a dictionary.
popitem() To remove the latest element of a dictionary.
get() To return the value of specified key in a dictionary.
update() To update a dictionary with another dictionary.
items() To return a list of dictionary's pairs.
setdefault() To return value of key if it is present in the dictionary and if key is not present in the dictionary then it insert key with a value.
copy() To return the copy of a dictionary.
keys() To return the list of all keys in the dictionary.
fromkeys() To return a dictionary with specified pair.

Built-in functions in Python dictionary

Here's the list of all built-in functions of python dictionary;

S.No Functions Description
1. any()

If any key of the dictionary is true then it returns true and if the dictionary is empty then it returns false.


2. all() If the list is empty or all the key of dictionary are true then it returns true.
3. sorted() To return a sorted version of keys of a dictionary.
4.len() To set the length or size of the dictionary.
5.cmp() Used for the comparison of items of two dictionaries.

Python Dictionary Comprehension

In python, dictionary comprehension allows us to create a new dictionary from the iterables of python in very concise and elegant manner. In dictionary comprehension, there's an expression i.e., pair which is following by statement written within the Curly brackets {}

# Python Dictionary Comprehension Example

sq = {a: a*a for a in range(5)}

print(sq)

Output

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

This code is equivalent to

sq = {}

for a in range(5):

    sq[a] = a*a

print(sq)

Output

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

In a dictionary comprehension, we can optionally use more if or for statements.

To filter out the items to form a new dictionary, an optional if statement is used.

Following are the examples of making a dictionary with odd items.

# Python Dictionary Comprehension with if conditional

sq = {a: a*a for a in range(10) if a % 2 == 1}

print(sq)

Output

{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

Dictionary Membership testing

In python dictionary, by using the Keywords, we can check if a specified is in the dictionary or not. But membership test is not for , it is only for .

# Membership Test for Dictionary Keys

sq = {1: 6, 3: 7, 15: 25, 6: 49, 9: 81}

# Output : True

print(1 in sq)

# Output : True

print(2 not in sq)

# membership tests for key only not value

# Output : False

print(69 in sq)

Output

True

True

False

Iterating Through a Dictionary 

By using the loop dictionary, we can iterate through each key.

# Iterating through a Dictionary

sq = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81, 10: 100}

for x in sq:

    print(sq[x])

Output

1

9

25

49

81

100

Conclusion

Above we have discussed about the python dictionary, how to create python dictionary, adding elements to a dictionary, accessing elements of dictionary, removing elements of dictionary, python dictionary methods and built-in function in dictionary. In python, dictionary is an unordered collection of elements and these elements are stored in [key:value] format.