Hi everyone, In this tutorial, we will learn about Python dictionary usages and its methods using examples.

1. What is a Python Dictionary?

Dictionary in Python is a mapping type data-structure that store data as a key:value pair. It is represented by curly-braces{}. Dictionary data-structure is highly used in optimization.

1.1 Python Dictionary :

  • If you want to represent a group of objects as key-value pairs then you can use the dictionary in python.
  • dictionaries are python implementation of abstract data types.
  • Like List data structure, dictionaries also grow and shrink in size as and when it requires and it can be easily updatable.
  • Dictionaries are unordered sets. Means, we can not expect the order of values as we inserted.
  • Dictionaries donโ€™t allow duplicate keys, but values can duplicate.

2. Dictionary Methods

Let’s see the dictionary methods and it’s usages.

2.1 Creating a dictionary

We can create a dictionary by assigning variable to curly braces {} or by using dict class constructor. Let’s create two dictionaries, one will be empty and one having few key:value pairs.

# imitializing dictionaries
d1 = {'apple':4,'banana':3,'mango':7}
d2 = dict()

# Printing them with their type
print(d1,type(d1))
print(d2,type(d2))

Output:

{'apple': 4, 'banana': 3, 'mango': 7} <class 'dict'>
{} <class 'dict'>

2.2ย  copy()

This will return a shallow copy of the dictionary. Let us copy the dictionary d1 into d2 using the copy() method.

d2 = d1.copy()
print("Dictionary D2 after copying data from d1\n",d2)

Output:

Dictionary D2 after copying data from d1
{'apple': 4, 'banana': 3, 'mango': 7}

We see that all the data form dictionary d1 is copied into the dictionary d2 above.

2.3 Changing a particular key-value

We can update the values of keys in the dictionary by indexing or by using the update() method. Let’s update our d2 dictionary by changing the value of key ‘apple’ to 10 using indexing and values of key ‘mango’ to 6 and insert a new key: value pair of ‘orange’:8 using update() method.

d2['apple']=10
d2.update(mango=6,orange=8)
print("Dictionary D2 after updating values\n",d2)

Output:

Dictionary D2 after updating values
{'apple': 10, 'banana': 3, 'mango': 6, 'orange': 8}

2.4 Accessing elements of a dictionary

There are various ways by which we can access elements from a dictionary. Let’s look at them one by one.

2.4.1 using get()

This method returns the value of a key from the dictionary. If a key is not present in the dictionary then this method will return None.

print(d2.get('banana'))
print(d2.get('pineapple'))

Output:

3
None

2.4.2 using keys()

This method returns a new view of the keys present in the dictionary.

view of keys of dictionary d2
dict_keys(['apple', 'banana', 'mango', 'orange'])

Output:

view of keys of dictionary d2
dict_keys(['apple', 'banana', 'mango', 'orange'])

2.4.3 using values()

This method returns a new view of the values present in the dictionary.

d2_vals = d2.values()
print("view of values of dictionary d2\n",d2_vals)

Output:

view of values of dictionary d2
dict_values([10, 3, 6, 8])

2.4.4 using items()

This method returns a new view as a tuple of (key,value) present in the dictionary.

d2_items = d2.items()
print("view of (key,value) of dictionary d2\n",d2_items)

Output:

view of (key,value) of dictionary d2
dict_items([('apple', 10), ('banana', 3), ('mango', 6), ('orange', 8)])

2.4.5 using setdefault(key,default)

This method returns the value of key specified as an argument, it takes 2 parameters:

  • key – The key whose value we want to access.
  • default – If the key is not present, then a new key will be created having value specified as default.
sd1 = d2.setdefault('orange','5')
sd2 = d2.setdefault('cherry','9')

print("val for sd1 'orange': ",sd1)
print("val for sd2 'cherry': ",sd2)
print("Dictionary d2:\n",d2)

Output:

val for sd1 'orange': 8
val for sd2 'cherry': 9
Dictionary d2:
{'apple': 10, 'banana': 3, 'mango': 6, 'orange': 8, 'cherry': '9'}

2.5 Deleting Values from the dictionary

There are various ways by which we can remove or delete elements from a dictionary. Let’s look at them one by one.

2.5.1 Using del dict[key]

If the specified key is in the dictionary, this method will delete the key-value pair, otherwise, it will raise a KeyError. Let’s delete the key ‘banana’ from our example.

del d2['banana']
print("Dictionary d2 after deleting 'banana'\n",d2)

Output:

Dictionary d2 after deleting 'banana'
{'apple': 10, 'mango': 6, 'orange': 8, 'cherry': '9'}

2.5.2 Using pop(key,default)

If the specified key is in the dictionary, this method removes it and return its value, else return default. If the default is not given and the key is not in the dictionary, a KeyError is raised. Let’s delete the key ‘orange’ in our example and print its value.

i = d2.pop('orange')
print(i)
print("Dictionary d2 after deleting 'orange'\n",d2)

Output:

>8
Dictionary d2 after deleting 'orange'
{'apple': 10, 'mango': 6, 'cherry': '9'}

2.5.3 Using popitem()

This method is used when we want to remove the item that is inserted last in the dictionary and get that key: value pair.

pi = d2.popitem()
print(pi)
print("Dictionary d2 after deleting the last inserted pair\n",d2)

Output:

('cherry', '9')
Dictionary d2 after deleting the last inserted pair
{'apple': 10, 'mango': 6}

2.5.3 Using clear()

This method will remove all the elements from the dictionary and it will be an empty dictionary after this operation.

d2.clear()
print("Dictionary d2 after clearing all elements\n",d2)

Output:

Dictionary d2 after clearing all elements
{}

In this tutorial, we have seen how to use different methods that we can apply on dictionary data-structure in Python. Hope you find this useful. If you have any doubts, feel free to ask in the comment section.

3. References

Happy Learning ๐Ÿ™‚