Accessing Dictionary Python | Example code

  • by

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"]]


Accessing Dictionary Python

Using get method

a_dict = {"A": 10, "B": 20, "C": 30}

x = a_dict.get("A")

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()

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()

Output: dict_values([10, 20, 30])

Get all elements of dictionary

Use 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()

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 (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.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.