Python Dictionary( Part II )
smart and simple
In the last article, we have discussed the dictionary in python.
Now we will discuss functions in dictionaries.
Functions we are going to see:
- fromkeys
- pop
- popitem
- setdefault
- update
________________________________________________________
let’s create a dictionary first
We can create a new dictionary using fromkeys() function with keys from iterable and values set to value.
let’s create a new dictionary.
pop():
It removes the specified key and returns the corresponding value. This is a risky function because it raises an error if the key is not present. To avoid error we can mention the value that we want to return when the key is absent.
let me show you how it raises an error if we provide the wrong key.
This is how you can handle an error.
you can provide any value like as I have provided ‘key not found’.
popitem():
In this function we don’t have to pass anything, it simply removes the last inserted pair from the dictionary.
setdefault():
It is used to insert key, value pair in the dictionary. If the key is already there in a dictionary then it returns that value for that key.
update():
an update is simply like extends function un lists. we can add one dictionary into another one.
You can also explore more functions in the dictionary.
Thanks for reading!!