Access Dictionary Items
To access dictionary items in Python, you can use either the keys or the items()
method. To access an item in the dictionary, refer to its key name inside square brackets. Choose the method that best suits your use case for access dictionary items. How to access value in Dictionary. There are many ways to access value:
- Accessing value by Keys
- Accessing Items using
items()
method - Using keys() method
- Using Values method
Here is how you can do it:
Accessing value by Keys
“a” is the key that you can access to dictionary. Its value is ‘1’ . Please look example below:
myDict = {"a": 1, "b": 2, "c": 3}
# Accessing value of key 'a'
value_a = myDict["a"]
print(value_a)
# Output: 1
Accessing Items using items()
method
You can use this method items() to access all item in dictionary either directly by their keys or by iterating over all key-value pairs using items()
. For loop is the best part to run through of each item in dictionary.
myDict = {"a": 1, "b": 2, "c": 3}
# Accessing all items
for key, value in myDict.items():
print(key,":", value)
#output
#a : 1
#b : 2
#c : 3
Using keys() method
This keys() is method and also keyword to get items from dictionary by this Keys(). It will return all lists in dictionary. Let’s see example below:
myDict = {"a": 1, "b": 2, "c": 3}
print(myDict.keys())
#output: dict_keys(['a', 'b', 'c'])
You can add item into dictionary by keys. ‘4’ will assign to myDict[‘d’], so this dictionary will extend another item ‘d’ which have key:’d’, value:4.
Here’s example:
myDict = {"a": 1, "b": 2, "c": 3}
myDict['d']=4;
print(myDict)
#output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Using Values method
It is similar to keys() method above. It will returns all values in dictionary.
myDict = {"a": 1, "b": 2, "c": 3}
print(myDict.values())
#output: dict_values([1, 2, 3])