general coding Flashcards
what does dict.get do?
Using get() with an existing key
It’s a safer way to retrieve values from a dictionary that helps avoid KeyError exceptions.
The basic syntax is: dict.get(key, default_value)
Here’s a simple example:
```python
user = {“name”: “Alice”, “age”: 30}
print(user.get(“name”)) # Output: “Alice”
print(user.get(“email”)) # Output: None
print(user.get(“email”, “no email found”)) # Output: “no email found”
~~~
The key difference between dict.get()
and direct access using square brackets (dict[key]
) is:
- dict[key]
raises a KeyError if the key doesn’t exist
- dict.get(key)
returns None if the key doesn’t exist
- dict.get(key, default)
returns the specified default value if the key doesn’t exist
This makes get() particularly useful when you want to handle missing keys gracefully without try/except blocks.
How can I turn all zeros in a 2d numpy array to 1 and all non zero elements to 1 with numpy function
Method 1: Using where()
Here are two simple ways to do this using NumPy functions:
```python
import numpy as np
result = np.where(arr == 0, 1, 0)
result = (arr == 0).astype(int)
~~~
Both methods will achieve the same result. For example:
```python
arr = np.array([[0, 5, 0],
[3, 0, 2],
[0, 1, 4]])
# [[1, 0, 1],
# [0, 1, 0],
# [1, 0, 0]]
~~~
The where()
method is often more readable, while the logical operator method might be slightly more performant. Choose whichever style you prefer!