Methods...

  • clear()
  • copy()
  • fromkeys()
  • get()
  • items()
  • keys()
  • pop()
  • popitem()
  • setdefault()
  • update()
  • values()

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)
Name
Nickname
Age
Nationality
Born?
Eye_Color
Favorite_Food
Sibling

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)
Ananya
Aisha
15
Indian
India
Brown
Pasta
Rashi

Adding and Removing items from a Dictionary

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)
{'Name': 'Ananya', 'Nickname': 'Aisha', 'Age': '15', 'Nationality': 'Indian', 'Born?': 'India', 'Eye_Color': 'Brown', 'Favorite_Food': 'Pasta', 'Sibling': 'Rashi', 'School': 'Del Norte'}

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)
{'Name': 'Ananya', 'Nickname': 'Aisha', 'Age': '15', 'Nationality': 'Indian', 'Eye_Color': 'Brown', 'Favorite_Food': 'Pasta', 'Sibling': 'Rashi'}