Dictionaries and its Built-in Methods in Python šŸ

October 13th, 2020 7 min read

Hello guys, in this post we are going to learn about Dictionaries in python and its Built-in methods. Now letā€™s start with the most simple question,

What is a dictionary in python ?

A dictionaries is an ordered, changable and indexed collection. A Dictionary is a key-value pair similar to json, here is an example of a dictionary,

student = {
	"name" : "Jhon Doe",
	"age"  : 25,
	"grades" : {
		"maths" : [100, 98],
		"science" : [95, 92],
	},
	"playsTennis" : True,
}

As you may have seen in the example that the student as a dictionary can have literally any valid data type as value of a key-value pair which includes String, Integer, Lists, Booleans, Dictionaries and so on.

You may have also noticed that the the format of a dictionary is as follows,

aDictionary = {
	"key" : "value",
	"key" : "value",
}

Read Data from Dictionary.

To read the data from the dictionary we can use any of the two ways,

1st way,


name = student["name"]
print(name)

# Result -> Jhon Doe

This way will find the key whose name is name and will print its value and if it doesnā€™t find that key it will throw an error, which may cause errors for the applications. To prevent all that mess we can use this second method,

2nd Way,


name = student.get("name")
print(name)

# Result -> Jhon Doe

In this way python will check whether name key exists, if it exists it will return it otherwise it will return None.


Write Data to Dictionary.

To add a new key-value pair to the dictionary we can use the following syntrax of update method which you can find below,


mydictionary = {}
mydictionary["someKey"] = "someValue"
print(mydictionary)
# Response -> {"someKey" : "someValue"}

Built-in Dictionary Methods

Now as we have covered the basics of the dictionary now letā€™s see what are some of the built in data methods for an dictionary,

  1. clear
  2. fromkeys
  3. get
  4. items
  5. keys
  6. pop
  7. popitem
  8. setdefault
  9. update
  10. values

Now letā€™s us start, since in most of the example we are going to use student dictionary so not to repeat it many times I will once again write it here so you can reference it,

student = {
	"name" : "Jhon Doe",
	"age"  : 25,
	"grades" : {
		"maths" : [100, 98],
		"science" : [95, 92],
	},
	"playsTennis" : True,
}

Clear - clear()

As its name suggests it clears that is remove all the item from dictionary and makes it empty,


student.clear()
print(student)
# Response -> {}

As you may have seen it when we use clear method on a dictionary it returns an empty {} dictionary.


FromKeys - fromkeys(keys, value)

There might be some situations where you want to create a dictionary with different keys but with same values so for such situations you may use fromkeys method. Letā€™s see an example,

somekeys = ('key1', 'key2', 'key3')
value = 123
newDict = dict.fromkeys(somekeys, value)
print(newDict)
# Response -> {'key1': 123, 'key2': 123, 'key3': 123}

As you may have seen it creates a dictionary with diffent keys and same values, this value can be any valid data type and the keys must be a tuple.


Get - get(key)

Get methods gets the value from the dictionary where the given key matches and returns it. Letā€™s see an example to understand it,

name = student.get("name")
print(name)
# Response -> Jhon Doe

The key passed as a argument to get method should be a string. If the key doesnā€™t exists it will return None as a response.


Items - items()

When items() is used on a dictionary object it will return a list wrapped dict_items object as a responese, it will return list of key-values pair in form of tuple. Letā€™s see it in an example,

items = student.items()
print(items)
# Response -> dict_items([('name', 'Jhon Doe'), ('age', 25), ('grades', {'maths': [100, 98], 'science': [95, 92]}), ('playsTennis', True)])

As you may have seen when items is used on a student it returns dict_items containing the values in form of tuple in a list. In the tuple inside the list the first value is key and second value is its value.


Keys - keys()

When we use keys on a dictionary it returns a list of keys of the dictionary wrapped in dict_keys class as a response to make it all clear letā€™s see an example,

keys = student.keys()
print(keys)
# Response -> dict_keys(['name', 'age', 'grades', 'playsTennis'])

As you may have seen above that when we use keys method on a dictionary object it returns a dict_keys contaning list of all the keys of the dictionary. I personally use this method when i donā€™t know about keys of the dictionary with which I am working.

Pop - pop(key)

When we use pop method on a dictionary it removes that key value pair from the dictionary, letā€™s see an example to understand it better.

student.pop("grades")
print(student)
#Response -> {'name': 'Jhon Doe', 'age': 25, 'playsTennis': True}

Using pop we removed grades key - value pair from student and left the rest untouched. Now letā€™s see popitem method.


Pop Item - popitem()

When popitem method is used on a dictionary to removes last key-value pair from dictionary. Now letā€™s see an example,

student.popitem()
print(student)
# Response -> {'name': 'Jhon Doe', 'age': 25, 'grades': {'maths': [100, 98], 'science': [95, 92]}}

It may be useful for the times when you want to remove last key-value pair from dictionary and donā€™t the value of last key. But try to use pop method abovepopitem as it will not cause errors if the structure of your dictionary changes.


Set Default - setdefault(key, value)

Set Default is used when, you are not sure whether the key-value pair exists and default value for it. Letā€™s make it clear be seeing an example,

student.setdefault("playsSoccer", True)
student.setdefault("playsTennis", False)
print(student)
# Response -> {'name': 'Jhon Doe', 'age': 25, 'grades': {'maths': [100, 98], 'science': [95, 92]}, 'playsTennis': True, 'playsSoccer': True}

In the above example we have used setdefault method on student two times, first time there was no such key called playsSoccer in our student dictionary so as a result it create playsSoccer : True in student.

When we see second use of setdefault method, we already have playsTennis key in our student dictionary and has value True but in setdefault method we have set value to False but as the key-value pair already exists as a result it will not overwrite the values of playsTennis key-value pair and will result in 'playsTennis': True,.


Update - update

Update method is used to add add a key-value pair, letā€™s make it clear by example,

student.update({"grade" : 11})
print(student)
# Response -> {'name': 'Jhon Doe', 'age': 25, 'grades': {'maths': [100, 98], 'science': [95, 92]}, 'playsTennis': True, 'grade': 11}

As you can see we added {"grade" : 11} key value pair to exisiting student dictionary. This method can be useful when you want to add another field to exising dictionary.

Note : The key - value pair passed to update method will be added to end of the first dictionary.


Values - values

Last but not least values, when it is used on a function it returns a list contaning all the values of dictionary wrapped by dict_values class. Letā€™s see this in action,

studentValues = student.values()
print(studentValues)
# Response -> dict_values(['Jhon Doe', 25, {'maths': [100, 98], 'science': [95, 92]}, True])

There is nothing to explain here, it is straight foreward.


You may also like: