- Dictionary is a data structure in python where data is stored as a key:value pair.
- Python dictionary is a ordered data structure since Python 3.7 i.e it will remember the order of insertion.
- Python dictionaries are mutable, we can change the value of a given key at any point of time.
- Dictionaries do not allow duplicate keys, since it uses hashing concept to store keys.
- Getting a value using key is a constant time operation O(1)
Dictionary Methods
- Given most of the commonly used in built methods in python. Note: The given methods are performed on the below dictionary
dictionary = dict() #declaring a dictionary
-
Inserting Key:Value pairs
- we don't have any exclisve function to do the job but we have a specific sintax to do it, as shown below,
dictionary['name'] = 'milk' dictionary['color'] = 'white' dictionary['source'] = 'cow' print(dictionary) # output : { 'name' : 'milk', 'color' : 'white', 'source' : 'cow' }
-
Accessing a Value using Key
- There are two ways you can access a value using key
- In python, there is a method
.get()
which takes a key as a argument, used to get a value as shown -
.get()
will return None , if key is not found in a dictionary
value = dictionary.get('name') print(value) #output: 'milk' value = dictionary.get('unknown_key') print(value) #output : None
-
The other way to access a value is using square brackets, the major difference between two methods is that it will through error if key is not found in dictionary.
name = dictionary['name'] print(name) #output: 'milk' name = dictionary['unknown_key] #output : KeyError: 'unknown_key'
Methods used while looping a Dictionary
-
.items()
:- This method generates dict_items which are tuples of key,value pairs. we can use tuple unpacking technique to access the key and values as shown.
items = dictionary.items() for key,value in items: print(key , value) #output: name milk color white source cow
-
.keys()
:- This method will return dict_keys which are list of keys in a dictionary. we can use loops to access all the keys.
keys = dictionary.keys() for key in keys: print(key) #output: name color source
-
.values()
:- This method will return dict_values which are list of values in a dictionary. we can use loops to access all the values.
keys = dictionary.values() for value in values: print(value) #output: 'milk' 'white' 'cow'
-
in
:- It is a keyword which can be used to find weather the key is present or not
- it will return a boolean value as shown
boolean = 'name' in dictionary print(boolean) #output: True boolean = 'unknown_key' in dictionary print(boolean) #output: False
-
.update()
:- This will take another dictionary as argument and addes it to the old one
new_dict = { 'food' : 'grass' } dictionary.update(new_dict) print(dictionary) #output: {'name': 'milk', 'color': 'white', 'source': 'cow', 'food': 'grass'}
-
.copy()
:- This method copies the entire dictionary to the new one
new_dict = dictionary.copy() print(new_dict) #output: {'name': 'milk', 'color': 'white', 'source': 'cow', 'food': 'grass'}
-
Update using Square Brackets
- We can append a key value pair in to a dictionary or we can update a value using the key as shown.
dictionary['source'] = 'buffelo' dictionary['year'] = '2015' print(dictionary) #output: {'name': 'milk', 'color': 'white', 'source': 'buffelo', 'food': 'grass' 'year': '2015'}
-
.pop('key')
:- This method will take key as a argument and will remove the key value pair from dictionary as shown
- It will return a value of the key that was poped
- This will through KeyError if key is not found
print(dictionary.pop('food')) #output: 'grass' print(dictionary.pop('unknown_key')) #output: unknown_key : 'unknown_key'
-
.popitem()
:- This method will pop the last item that was inserted and will return a tuple of key and value
- This will return KeyError if dictionary is empty
print(dictionary.popitem()) #output:('year', '2015')
-
.clear()
:- This method will clear the dictionary and returns None
dictionary.clear() print(dictionary) #output: {}
-
defaultdict
:- This function can be imported from collections module in python
- this will take a customized function reference as input, when ever tha key is not present in dictionary it will exicute the custom function.
from collections import defaultdict def default_fun(): print('key is not present') dct = defaultdict(default_fun) print(dct['unknown_key']) #output: key is not present
Top comments (0)