Dictionary Methods!
Looping through a dictionary
When we loop through a dictionary, we can also decide if we want just the values or the keys printed. Lets say that we want just the keys of the dictionary to be printed, we would have to type
for a in dictionaryname.keys(): print(a)
In the code above we have used a for loop to go through the dictionary and print only the keys.
Ananya = {
"Name": "Ananya",
"Nickname": "Aisha",
"Age": "15",
"Nationality": "Indian",
"Born?": "India",
"Eye_Color": "Brown",
"Favorite_Food" : "Pasta",
"Sibling" : "Rashi"
}
for a in Ananya.keys():
print(a)
Now lets say we want just the values, in order to print just the values, we would type the same line of code we did for keys, expect one word will change, keys to values for a in dictionaryname.values(): print(a)
Ananya = {
"Name": "Ananya",
"Nickname": "Aisha",
"Age": "15",
"Nationality": "Indian",
"Born?": "India",
"Eye_Color": "Brown",
"Favorite_Food" : "Pasta",
"Sibling" : "Rashi"
}
for a in Ananya.values():
print(a)
In order to add another index into a dictionary we say: dictionaryname["key"] = "value" print(thidictionaryname)
Ananya = {
"Name": "Ananya",
"Nickname": "Aisha",
"Age": "15",
"Nationality": "Indian",
"Born?": "India",
"Eye_Color": "Brown",
"Favorite_Food" : "Pasta",
"Sibling" : "Rashi"
}
Ananya["School"] = "Del Norte"
print(Ananya)
In order to remove an index, we use the pop method
Ananya = {
"Name": "Ananya",
"Nickname": "Aisha",
"Age": "15",
"Nationality": "Indian",
"Born?": "India",
"Eye_Color": "Brown",
"Favorite_Food" : "Pasta",
"Sibling" : "Rashi"
}
Ananya.pop("Born?")
print(Ananya)