Hello all,
In this post, we will talk about some of the useful functions of a dictionary in python.
But before we dive into functions we will look for what is a dictionary in python.
What is Dictionary in Python?
- Dictionary is a Composite data type in Python.
- Dictionary is all about pair.
- We can store different types of value in a dictionary.
- A Dictionary is very easy to use as it is mutable in nature.
- A Dictionary can grow and shrink as per our needs.
- A Dictionary can contain another dictionary, list or tuple as value.
Defining Dictionary :
You can define an empty dictionary by :
Add Value and Delete Value from Dictionary :
- To add an entry in a dictionary we do like
var dict = {}
dict['key'] = value
print(dict)
{'key':value}
- If we try to add value with an already existing key, then python will replace the new value with old value for that key in the dictionary.
- To remove an entry from a dictionary
var dict = {}
dict['key'] = value
print(dict)
{'key':value}
#to delete
del dict['key']
print(dict)
{}
Functions of Dictionary :
1.len()
2.keys()
3.values()
4.update()
5.clear()
1.len() :
- len() functions returns length of dictionary.
- The length of the dictionary means a number of key, value pairs in a dictionary.
dict = {}
dict['key'] = "value";
print(len(dict))
# Output
# 1
2.keys() :
- keys() function is used when we want to list out all the keys of a dictionary.
dict = {}
dict['1'] = "One";
dict['2'] = "two";
dict['3'] = 3
print(dict.keys())
# Output
# dict_keys(['1', '2', '3'])
3.values() :
- values() function gathers all the values from the dictionary by separating keys, as a list.
dict = {}
dict['1'] = "One";
dict['2'] = "two";
dict['3'] = 3
print(dict.values())
# Output
# dict_values([3, 'two', 'One'])
4.update() :
- update() is very useful function of dictionary.
- This function is used to add new value/values in a dictionary.
- We can append two dictionaries with the help of update().
d1 = {'a': 10, 'b': 20, 'c': 30}
d2 = {'b': 200, 'd': 400}
d1.update(d2)
print(d1)
# Output
# {'a': 10, 'b': 200, 'c': 30, 'd': 400}
- In this example, you can notice that we already have 'b' as a key in our d1 dictionary so update() will not add 'b' as a new key instead of that it will overwrite the new value with old value for key 'b'.
5.clear() :
- As the name suggests, clear() makes the dictionary empty.
d1 = {'a': 10, 'b': 20, 'c': 30}
print(d1)
d1.clear()
print(d1)
# Output
# {'c': 30, 'b': 20, 'a': 10}
# {}
Comments
Post a Comment