To determine if a specified key is present in a dictionary use the in
keyword:
Check if "model" is present in the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
To determine how many items (key-value pairs) a dictionary has, use the len()
method.
Print the number of items in the dictionary:
print(len(thisdict))
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)