Just use the key inside square brackets [ ] to get the Access Dictionary Items in Python. You can also use the get() method to access dict elements.
Example accessing dictionary in Python
Simple examples code.
Accessing Items using square brackets
Get the value of the element using a key.
a_dict = {"A": 10, "B": 20, "C": 30}
x = [a_dict["A"]]
print(x)
Output:
Using get method
a_dict = {"A": 10, "B": 20, "C": 30}
x = a_dict.get("A")
print(x)
Output: 10
Get all keys of the dictionary
The keys() method will access and return a list of all the keys in the dictionary.
a_dict = {"A": 10, "B": 20, "C": 30}
x = a_dict.keys()
print(x)
Output: dict_keys([‘A’, ‘B’, ‘C’])
Get all Values Access from dictionary
The values() method gives access and returns a list of all the values in the dictionary.
a_dict = {"A": 10, "B": 20, "C": 30}
x = a_dict.values()
print(x)
Output: dict_values([10, 20, 30])
Get all elements of dictionary
Using the items() method will return each item (kye value pair) in a dictionary, as tuples in a list.
a_dict = {"A": 10, "B": 20, "C": 30}
x = a_dict.items()
print(x)
Output: dict_items([(‘A’, 10), (‘B’, 20), (‘C’, 30)])
Do comment if you have any questions or doubts on this Python dictionary tutorial.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.