What are dictionaries in python?
A collection which is unordered, changeable and indexed is known as a dictionary in python. It takes two elements where one is the key and the other one is value. However, the keys should be unique within a dictionary while values may not be. The data type of the values can be anything but the keys must be of an immutable data type such as strings, numbers, or tuples.
Syntax :
To separate a key from its value a colon (:) is used whereas the items are separated by commas. The whole thing is enclosed in curly braces.
Example : thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict) An empty dictionary can be written like: Dict = {}
Accessing dictionary items
The dictionary items can be accessed by referring to its key name.
Example: Get the value of the “model” key: x = thisdict["model"] You can also access the items by using a method called get() like: x = thisdict.get("model")
Change values
Changing the values in dictionaries is very easy. The value of a specific item can be changed by referring to its key name:
Example: change the “year” to 2018: thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict["year"] = 2018
Below are some actions that can be performed on dictionaries in python:
Adding items
This can be done by using a new index and assigning a value to it.
Example: thisdict["color"] = "red" print(thisdict)
Removing items
There are many methods that are used for removing items.
Example: del thisdict["model"] thisdict.pop("model")
Using loops
You can use a for loop through a dictionary.
Example 1: for x in thisdict: print(x)
This loop returns the values of the keys.
Example 2: for x in thisdict: print(thisdict[x])
This loop returns all the values one by one.