Python Dictionaries store data values in key : value pairs.
car = { "brand" : "Tesla", "model" : "S" }
◽️ Dict are ordered (Py 3.7), it means that the items have a defined order.
◽️ Cannot have two items with the same key.
◽️ We can update, add or remove items in the dictionary.
◽️ Values in dict items can be of any data type.
Let's now go through all the Python essential functions:
1⃣ clear()
It removes all the elements from a dictionary.
car = { "brand": "Tesla" }
car.clear()
2⃣ copy()
It returns a copy of the specified dictionary.
car = { "brand": "Tesla" }
x = car.copy()
3⃣ get()
It returns the value of the item with the specified key
car = { "brand": "Tesla" }
x = car.get("model") x -> Tesla
4⃣ fromkeys()
It returns a dictionary with the specified keys and the specified value
x = ('key1', 'key2', 'key3') y = 0
thisdict = dict.fromkeys(x, y)
5⃣ keys()
It returns the list of keys in dict.
car = { "brand": "Tesla" }
car.keys()
6⃣ pop()
It removes the specified item from the dictionary.
car = { "brand": "Tesla" }
car.pop( 'brand' )
7⃣ update()
It inserts the specified items to the dictionary. Specified items can be a dictionary, or an iterable object with key value pairs.
car = { "brand": "Tesla" }
car.update({"color": "Black"})
8⃣ values()
It returns the list of values in dictionary
car = { "brand": "Tesla" }
car.values()
9⃣ setdefault()
It returns the value of the item with the specified key.
If the key does not exist, inserts the key, with the specified value.
car = { "brand": "Tesla" }
car.setdefault("color", "white")
That covers all the #python important dictionary functions Hope you liked it and don't forget to ♥️ it.