I have created a for loop that loops through each key and value in the data dictionary items. Inside the for loop, I have created an if statement that checks if the value is not equal to "student". Inside the if statement, I am using the capitalize() method to update the string values for all strings that are not "student" so that their first letter is capitalized:
data = {
"first_name": "brian",
"last_name": "johnson",
"occupation": "student"
}
for key, value in data.items():
if value != "student":
value = data[value].capitalize()
print(data)
When I print outside the loop I get KeyError: 'brian' Could anyone kindly tell me where I am going wrong?? Thank you so much!
Using data[x] calls the value from key x, so what you currently have is attempting to use the values as keys. It will work if you change the code to
data = {
"first_name": "brian",
"last_name": "johnson",
"occupation": "student"
}
for key, value in data.items():
#use **data[key]** to call the **value**
if data[key] != "student":
data[key] = data[key].capitalize()
print(data)