Functions and methods of dictionaries
Functions and methods of dictionaries
In Python, dictionaries have built-in functions and methods that allow you to manipulate and work with dictionary objects. Here's an overview of some common functions and methods associated with dictionaries:
### Functions:
1. `len()`
- Returns the number of key-value pairs in the dictionary.
```python
my_dict = {'name': 'Alice', 'age': 16}
print(len(my_dict)) # Output: 2
```
### Methods:
1. `dict.clear()`
- Removes all key-value pairs from the dictionary.
```python
my_dict = {'name': 'Alice', 'age': 16}
my_dict.clear()
print(my_dict) # Output: {}
```
2. `dict.get(key[, default])`
- Returns the value associated with the specified key, or a default value if the key does not exist.
```python
my_dict = {'name': 'Alice', 'age': 16}
print(my_dict.get('name')) # Output: Alice
print(my_dict.get('city', 'Unknown')) # Output: Unknown
```
3. `dict.items()`
- Returns a view of key-value tuples as a list of tuples.
```python
my_dict = {'name': 'Alice', 'age': 16}
print(my_dict.items()) # Output: dict_items([('name', 'Alice'), ('age', 16)])
```
4. `dict.keys()`
- Returns a view of keys in the dictionary as a list.
```python
my_dict = {'name': 'Alice', 'age': 16}
print(my_dict.keys()) # Output: dict_keys(['name', 'age'])
```
5. `dict.values()`
- Returns a view of values in the dictionary as a list.
```python
my_dict = {'name': 'Alice', 'age': 16}
print(my_dict.values()) # Output: dict_values(['Alice', 16])
```
6. `dict.pop(key[, default])`
- Removes the key and returns its associated value. If the key is not found, it returns the default value or raises a KeyError if no default is provided.
```python
my_dict = {'name': 'Alice', 'age': 16}
value = my_dict.pop('age')
print(value) # Output: 16
```
7. `dict.popitem()`
- Removes and returns an arbitrary key-value pair as a tuple. Raises a KeyError if the dictionary is empty.
```python
my_dict = {'name': 'Alice', 'age': 16}
item = my_dict.popitem()
print(item) # Output: ('age', 16)
```
8. `dict.update(iterable)`
- Updates the dictionary with key-value pairs from another iterable (usually another dictionary).
```python
my_dict = {'name': 'Alice', 'age': 16}
my_dict.update({'city': 'New York', 'age': 17})
print(my_dict) # Output: {'name': 'Alice', 'age': 17, 'city': 'New York'}
```
9. `dict.setdefault(key[, default])`
- Returns the value associated with the specified key, or inserts the key with the default value if it doesn't exist.
```python
my_dict = {'name': 'Alice'}
print(my_dict.setdefault('age', 16)) # Output: 16
print(my_dict) # Output: {'name': 'Alice', 'age': 16}
```
These functions and methods are fundamental for manipulating and working with dictionaries in Python, allowing you to add, retrieve, update, and remove key-value pairs efficiently.
Comments
Post a Comment