Python Programming - Variables
- Variables - General Questions
my_dict = {"a": 1, "b": 2}
my_dict["c"] = 3
print(my_dict)
In this code, a dictionary my_dict is defined with two key-value pairs.
The second line adds a new key "c" with the value 3 to the dictionary.
When the modified dictionary is printed to the console, the output is {"a": 1, "b": 2, "c": 3}.
my_string = "hello world"
print(my_string[1:8:2])In this code, a string my_string is defined with the value "hello world".
The second line uses slice notation to select every second character from the substring starting at index 1 and ending at index 8.
The expression my_string[1:8:2] selects the characters with the following indices: 1, 3, 5, and 7, which correspond to "el o" in the string "hello world".
The resulting substring is "el o", which is then printed to the console.
The del keyword can be used to remove a key-value pair from a dictionary. To delete the pair with key "key", you can use the syntax del my_dict["key"].
Other methods for removing key-value pairs from a dictionary include using the pop() method or the clear() method.
1. Using the pop() method:
my_dict.pop("key")
This method removes the key and returns its value. If the key is not found, a specified default value is returned, or a KeyError is raised.
2. Using the clear() method:
my_dict = {"a": 1, "b": 2, "c": 3}
my_dict.clear()
print(my_dict) # Output: {}
It does not delete individual key-value pairs, but rather empties the entire dictionary.
my_list = [1, 2, 3]
my_list.append([4, 5])
print(my_list)In this code, a list my_list is defined with the values [1, 2, 3].
The second line appends the list [4, 5] to my_list.
When the modified list is printed to the console, the output is [1, 2, 3, [4, 5]].
my_dict = {"a": 1, "b": 2}
del my_dict["c"]
print(my_dict)The given code attempts to delete the key "c" from the dictionary my_dict.
However, since "c" is not a valid key in the dictionary, the del my_dict["c"] operation will raise a KeyError.
Therefore, the output of the code will be a KeyError:
Traceback (most recent call last):
File "example.py", line 2, in
del my_dict["c"]
KeyError: 'c'