- Python Features
- Python Installation
- PyCharm Configuration
- Python Variables
- Python Data Types
- Python If Else
- Python Loops
- Python Strings
- Python Lists
- Python Tuples
- Python List Vs Tuple
- Python Sets
- Python Dictionary
- Python Functions
- Python Files I/O
- Read Write Excel
- Read Write JSON
- Read Write CSV
- Python OS Module
- Python Exceptions
- Python Datetime
- Python Collection Module
- Python Sys Module
- Python Decorator
- Python Generators
- Python OOPS
- Python Numpy Module
- Python Pandas Module
- Python Sqlite Module
Python Dictionary Introduction
Python dictionaries are a built-in data type used to store key-value pairs. They are mutable and allow for efficient retrieval and manipulation of data. Dictionaries are defined using curly braces ({}) and contain comma-separated key-value pairs. Here’s an example:
person = {
"name": "Yash",
"age": 23,
"occupation": "Architect"
}
In this example, “name”, “age”, and “occupation” are the keys, and “Yash”, 23, and “Architect” are the corresponding values. The keys must be unique within a dictionary, but the values can be of any data type.
You can access the values in a dictionary by using the corresponding key:
print(person["name"]) # Output: Yash
print(person["age"]) # Output: 23
print(person["occupation"]) # Output: Architect
Features of Python Dictionary:
- Key-Value Pairs: Python dictionaries are a collection of key-value pairs, where each key is unique and associated with a value.
- Mutable: Dictionaries are mutable, which means you can modify, add, or remove key-value pairs after the dictionary is created.
- Dynamic Sizing: Dictionaries in Python can dynamically resize to accommodate an arbitrary number of key-value pairs.
- Unordered: Dictionaries are unordered, meaning the items are not stored in any particular order.
- Efficient Data Retrieval: Dictionaries provide fast and efficient data retrieval based on the key.
- Various Data Types: Python dictionaries can store values of any data type, including integers, floats, strings, lists, tuples, other dictionaries, and even custom objects. This flexibility allows you to organize and structure data in a way that suits your specific needs.
- Membership Testing: Dictionaries provide efficient membership testing using the `in` operator. You can check if a key exists in a dictionary without iterating over all the items, making it convenient for conditional operations.
- Uniqueness of Keys: Python dictionary keys must be unique. This property ensures that each key is associated with a single value, preventing duplicate entries
Python Dictionary Functions/Methods:
- `len()` function: Returns the number of key-value pairs in a dictionary.
dictionary = {"name": "Yash", "age": 23}
print(len(dictionary)) # Output: 2
- `keys()` method: Returns a view object that contains all the keys in a dictionary.
dictionary = {"name": "Yash", "age": 23, "occupation": "Architect"}
keys = dictionary.keys()
print(keys)
# Output: dict_keys(['name', 'age', 'occupation'])
- `values()` method: Returns a view object that contains all the values in a dictionary.
dictionary = {"name": "Yash", "age": 23, "occupation": "Architect"}
values = dictionary.values()
print(values)
# Output: dict_values([Yash, 22,Architect])
- `items()` method: Returns a view object that contains all the key-value pairs as tuples in a dictionary.
dictionary = {"name": "Yash", "age": 23, "occupation": "Architect"}
items = dictionary.items()
print(items) # Output: dict_items([('name', 'Yash'), ('age',23), ('occupation', 'Architect')])
- `get()` method: Returns the value associated with a given key. It allows specifying a default value to be returned if the key is not found.
dictionary = {"name": "Yash", "age": 23, "occupation": "Architect"}
print(dictionary.get("name")) # Output: Yash
print(my_dict.get("city", "N/A")) # Output: N/A (default value for non-existent key)
- `pop()` method: Removes and returns the value associated with a given key. It takes the key as an argument and removes the corresponding key-value pair from the dictionary.
dictionary = {"name": "Yash", "age": 23, "occupation": "Architect"}
removed_value = dictionary.pop("age")
print(removed_value) # Output : 25
print(dictionary) # Output: {'name': 'Yash', 'occupation': 'Architect'}
- `update()` method: Merges the key-value pairs from another dictionary into the current dictionary. If a key already exists, the value is updated; otherwise, a new key-value pair is added.
dictionary = {"name": "Yeah", "age": 23}
new_dict = {"occupation": "Architect", "city": "Pune"}
dictionary.update(new_dict)
print(dictionary) # Output: {'name': 'Yash', 'age': 23, 'occupation': 'Architect', 'city': 'Pune'}
- `clear()` method: Removes all key-value pairs from a dictionary, making it empty.
dictionary = {"name": "Yash", "age": 23, "occupation": "Architect"}
dictionary.clear()
print(dictionary) # Output: {}
Python Dictionary operators:
- Membership Operators:
– `in` operator: Returns `True` if a key exists in the dictionary, otherwise `False`.
– `not in` operator: Returns `True` if a key does not exist in the dictionary, otherwise `False`.
dictionary = {"name": "Yash", "age": 23, "occupation": "Architect"}
print("name" in dictionary) # Output: True
print("Company" not in dictionary) # Output: True
print("age" in dictionary.keys()) # Output: True
print("Engineer" in dictionary.values()) # Output: False
- Comparison Operators:
– `==` operator: Returns `True` if two dictionaries have the same key-value pairs, otherwise `False`.
– `!=` operator: Returns `True` if two dictionaries have different key-value pairs, otherwise `False`.
dict1 = {"name": "Yash", "age": 23}
dict2 = {"age": 23, "name": "Yash"}
print(dict1 == dict2) # Output: True (order of key-value pairs doesn't matter)
print(dict1 != dict2) # Output: False (key-value pairs are the same)
- Assignment Operator:
– `=` operator: Assigns a dictionary to a variable.
dictionary = {"name": "Yash", "age": 23, "occupation": "Architect"}
- Deletion Operator:
– `del` operator: Deletes an entire dictionary or a specific key-value pair.
dictionary = {"name": "Yash", "age": 23, "occupation": "Architect"}
del dictionary ["age"]
print(dictionary) # Output: {'name': 'Yash', 'occupation': 'Architect'}