Google News
logo
Python Program to Access the items of a dictionary
You can access the items of a dictionary using the keys. Here's an example :
Program :
# create a dictionary
my_dict = {"apple": 2, "banana": 3, "orange": 4}

# access an item by key
print(my_dict["apple"])
print(my_dict["orange"])
Output :
2
4
You can also use the `get()` method to access items by key. This method returns `None` if the key is not found in the dictionary.
Program :
# create a dictionary
my_dict = {"apple": 2, "banana": 3, "orange": 4}

# access an item by key using get()
print(my_dict.get("apple"))
print(my_dict.get("pear"))
Output :
2
None
You can also use the `items()` method to access all the items in a dictionary.
# create a dictionary
my_dict = {"apple": 2, "banana": 3, "orange": 4}

# access all items using items()
for key, value in my_dict.items():
    print(key, value)​


Output :

apple 2
banana 3
orange 4