Access Items
Accessing Dictionary Items:
I. Accessing Single Values:
Values in a dictionary can be accessed using keys. We can access dictionary values by mentioning keys either in square brackets or by using the get
method.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info['name'])
print(info.get('eligible'))
Output:
Karan
True
II. Accessing Multiple Values:
We can print all the values in the dictionary using the values()
method.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info.values())
Output:
dict_values(['Karan', 19, True])
III. Accessing Keys:
We can print all the keys in the dictionary using the keys()
method.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info.keys())
Output:
dict_keys(['name', 'age', 'eligible'])
IV. Accessing Key-Value Pairs:
We can print all the key-value pairs in the dictionary using the items()
method.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info.items())
Output:
dict_items([('name', 'Karan'), ('age', 19), ('eligible', True)])