You can access a dictionary item value using its key with square brackets ([]
).
company_dictionary = {
"name": "Google",
"country": "USA",
"start_year": 1995
}
company_name = company_dictionary["name"]
print(company_name)
'Google'
In the above example, we are accessing the name
of a company by using the key of the dictionary, so as in the output, you can see the company name is "Google"
.
You can use the get()
function to access a dictionary item's value.
company_dictionary = {
"name": "Google",
"country": "USA",
"start_year": 1995
}
company_name = company_dictionary.get("name")
print(company_name)
'Google'
Here, we are accessing the name of a company by using the key of the dictionary with the get()
function, and in the output, we get the company name as a "Google"
.
The key()
function returns all the keys of the dictionary.
company_dictionary = {
"name": "Google",
"country": "USA",
"start_year": 1995
}
dictionary_keys = company_dictionary.keys()
print(dictionary_keys)
dict_keys(['name', 'country', 'start_year'])
In the above example, in the output, you can see the list of all keys in the dictionary.
The values()
function returns all the values in the dictionary.
company_dictionary = {
"name": "Google",
"country": "USA",
"start_year": 1995
}
dictionary_values = company_dictionary.values()
print(dictionary_values)
dict_values(['Google', 'USA', 1995])
Here, in the output, you can see the list of all values in the dictionary.
The items()
function returns all key-value pairs in the dictionary.
The items()
function returned key-value pairs as in the tuple, and all tuples exist within a list.
company_dictionary = {
"name": "Google",
"country": "USA",
"start_year": 1995
}
dictionary_items = company_dictionary.items()
print(dictionary_items)
dict_items([('name', 'Google'), ('country', 'USA'), ('start_year', 1995)])
As you can see in the output, the items()
function returned all key-value pairs from the dictionary.
To check the given key is present in the dictionary, use in
keyword with the if
condition check.
company_dictionary = {
"name": "Google",
"country": "USA",
"start_year": 1995
}
if "name" in company_dictionary:
print("There is a name key in the dictionary.")
else:
print("There is no name key in the dictionary.")
There is a name key in the dictionary.
Using the "in"
keyword, we check if the "name"
key exists in the dictionary, if it exists, then print the text "There is a name key in the dictionary."
else print "There is no name key in the dictionary."
.
You can see in the output that the "name"
key exists in the dictionary that's why it prints the text "There is a name key in the dictionary."
.