Dictionary in Python
Published: 2023-05-10 17:23:40


* 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`
1. ### 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' }
	 ```
2. ###  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
3. ### `.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
	```
4. ### `.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
	```
5. ### `.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'
	```
	
6. ### `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
	```
7. ### `.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'}
	```
8. ### `.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'}
	 ```
9. ### 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'}
	```

10. ### `.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'
	```
11. ### `.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')
	```
12. ### `.clear()`:
	* This method will clear the dictionary and returns None
	```
		dictionary.clear() 
		print(dictionary)
		#output: {}
	```
13. ### `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
	```
## References:
* [Python Docs](https://docs.python.org/3/tutorial/datastructures.html)
* [w3 Schools](https://www.w3schools.com/python/python_dictionaries.asp)