Dictionaries
This commit is contained in:
56
src/basic/dictionaries.py
Normal file
56
src/basic/dictionaries.py
Normal file
@@ -0,0 +1,56 @@
|
||||
from typing import Any
|
||||
|
||||
|
||||
car: dict[str, Any] = {
|
||||
"brand": "Ford",
|
||||
"model": "Mustang",
|
||||
"year": 1964,
|
||||
'service_months': [1, 3, 4]
|
||||
}
|
||||
|
||||
# print(type(car))
|
||||
# print(car)
|
||||
# print(car['brand'])
|
||||
|
||||
# print(car['name']) #gives error because the name the property isn't present in this dict
|
||||
|
||||
# print(car.keys()) # give all keys
|
||||
|
||||
# print(car.values())
|
||||
# car["color"] = "white" # Adding a new item to the original dictionary
|
||||
# print(car)
|
||||
|
||||
# car.update({"year": 2020}) # Update the "year" of the car by using the update() method
|
||||
# print(car)
|
||||
# car.update({"color": "red"})
|
||||
# print(car)
|
||||
# car.pop("model") # The pop() method removes the item with the specified key name
|
||||
# print(car)
|
||||
# del car["year"]
|
||||
# car.clear() # The clear() method empties the dictionary:
|
||||
|
||||
# print(car.get('brand')) # Returns the value of the specified key
|
||||
# print(car.copy()) # Returns a copy of the dictionary
|
||||
|
||||
# fromkeys # Returns a dictionary with the specified keys and value
|
||||
|
||||
# Syntax dict.fromkeys(keys, value)
|
||||
x = ('key1', 'key2', 'key3')
|
||||
y = 0
|
||||
|
||||
thisdict = dict.fromkeys(x, y)
|
||||
|
||||
|
||||
print(thisdict)
|
||||
|
||||
# setdefault
|
||||
car = {
|
||||
"brand": "Ford",
|
||||
"model": "Mustang",
|
||||
"year": 1964
|
||||
}
|
||||
|
||||
# If the key does not exist, insert the key, with the specified value, see example below
|
||||
x = car.setdefault("model", "Bronco1")
|
||||
|
||||
print(x)
|
||||
@@ -47,3 +47,9 @@ a.pop(1) # Removes the element at index 1 (20)
|
||||
|
||||
# Deletes the first element (10)
|
||||
del a[0]
|
||||
|
||||
|
||||
my_list: list[int] = [1, 2, 3, 4, 5, 6, 7, 8, 9]
|
||||
|
||||
my_list.sort(reverse=True)
|
||||
print(my_list)
|
||||
|
||||
Reference in New Issue
Block a user