Python Dictionary Data Structure and it's methods
Published: 2023-05-10 18:51:38

## Dictionary
-   In Python, a dictionary is a built-in data structure that is used to store a collection of key-value pairs.
- Each key in a dictionary maps to a corresponding value, similar to a real-world dictionary where each word 		maps to a definition.
-   Dictionary is a  __ordered__  data structure  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.

```python
my_dict = {
...     "name": "John",
...     "age": 30,
...     "city": "New York"
... }
>>> my_dict
{'name': 'John', 'age': 30, 'city': 'New York'}

```
## Dictionary Methods of Python

### 1. Inserting keys using dicitonary_name["key_name] = value :-
```python
my_dict = {
... 'name' : 'John',
... 'age': 30,
... 'city': 'New York'
... }
>>> my_dict
{'name': 'John', 'age': 30, 'city': 'New York'}
>>> my_dict['surname'] = 'Wick'
>>> my_dict
{'name': 'John', 'age': 30, 'city': 'New York', 'surname': 'Wick'}
```

###  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
```python
>>> my_dict.get("name")
'John'
>>> my_dict.get('occupation')
>>> 
```
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.
```python
>>> my_dict['occupation']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'occupation'
```
### Methods used while iterating over a Dictionary

###  1) .items() :-
This method returns an object which is of tuple form which includes key and value. Tuple - (key, value) object.
We will have to use an iterating loop to extract these tuples
example:-
```python
>>> my_dict = {
...     "name": "John",
...     "age": 30,
...     "city": "New York",
...     "country": "USA",
... }
>>> for key,value in my_dict.items():
...     print(key,value)
... 
name John
age 30
city New York
country USA
```

###  2) .keys() :-
The `.keys()` method is used to return a view object that contains the keys of a dictionary. Each key in the view object is a string that corresponds to a key in the original dictionary.
```python
>>> for keys in my_dict.keys():
...     print(keys)
... 
name
age
city
country
```
###  3) .values() :-
The `.values()` method is used to return a object that contains the values for respective keys of a dictionary. 
example:-
```python
>>> for values in my_dict.values():
...     print(values)
... 
John
30
New York
USA

```
###  4) in :-
Returns a boolean value for whether a key is present in dictionary or not.
example:-
```python
>>> print('occupation' in my_dict)
False
>>> print('name' in my_dict)
True
```
### 5) update() :-
The `.update()` method is used to update a dictionary with new key-value pairs from another dictionary or an iterable of key-value pairs. If a key in the new dictionary already exists in the original dictionary, its corresponding value is updated with the new value.
```python
>>> my_dict = {'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA'}
>>> new_dict = {'city': 'Los Angeles', 'phone': '555-1234'}
>>> my_dict.update(new_dict)
>>> my_dict
{'name': 'John', 'age': 30, 'city': 'Los Angeles', 'country': 'USA', 'phone': '555-1234'}

```
### 6) .copy() :-
The `.copy()` method is used to create a shallow copy of a dictionary. It returns a new dictionary with the same key-value pairs as the original dictionary. 
Any changes made to the new dictionary isn't reflected in original dictionary.
example:-
```python
>>> my_dict = {'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA'}
>>> new_dict = my_dict.copy()
>>> 
>>> new_dict['city'] = 'Los Angeles'
>>> my_dict
{'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA'}
>>> new_dict
{'name': 'John', 'age': 30, 'city': 'Los Angeles', 'country': 'USA'}
```
### 7) .pop(key) :-

The `.pop()` method is used to remove and return the value for a given key in a dictionary. 
Key-Value pair is removed from dictionary.
```python
my_dict
{'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA'}
>>> my_dict.pop('age')
30
>>> my_dict
{'name': 'John', 'city': 'New York', 'country': 'USA'}
>>> my_dict.pop('work')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'work'
```
### 8) .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
```python
>>> my_dict['age']=35
>>> my_dict
{'name': 'John', 'city': 'New York', 'country': 'USA', 'age': 35}
>>> my_dict.popitem()
('age', 35)
>>> my_dict
{'name': 'John', 'city': 'New York', 'country': 'USA'}
```
### 9) .clear() :-
Returns NONE after clearing the dictionary
example:-
```python
>>> my_dict
{'name': 'John', 'city': 'New York', 'country': 'USA'}
>>> my_dict.clear()
>>> my_dict
{}
```

### 10) .setdefault() 
Returns the value of the item with the specified key

example:- 
```python
>>> my_dict
{}
>>> my_dict.setdefault('name' , 'John')
'John'
>>> my_dict
{'name': 'John'}
```

## References

[Python docs official](https://docs.python.org/3/tutorial/datastructures.html#dictionaries)
[W3Schools](https://www.w3schools.com/python/python_dictionaries.asp)