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.
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 :-
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
>>> 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.
>>> 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:-
>>> 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.
>>> 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:-
>>> 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:-
>>> 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.
>>> 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:-
>>> 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.
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
>>> 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:-
>>> 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:-
>>> my_dict
{}
>>> my_dict.setdefault('name' , 'John')
'John'
>>> my_dict
{'name': 'John'}
Top comments (0)