Python Forum

Full Version: How to capitalize in dictionary
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone. I ran into a problem. I would like words in the dictionary that are written in lowercase to be displayed in uppercase. I thought I found a solution but it only works with a list.
shopping = {
    "bakery": ["bread","doughnut", "cake",],
    "grocery": ["carrot","pear", "thyme"]
}
for i in shopping:
  print(i, shopping[i])
A function which i found that unfortunately does not work in the dictionary. Example for a list:
my_list = ["bread", "butter"]
my_list = [element.capitalize()for element in my_list]
print(my_list)
And this is good
How to write a function and where, to have carrots, thyme and other products written with capital letters? Greetings
You have lists for dictionary values, so must access each element in "grocery" and save back as value.title()
example:
pond_animals = {
    "fish": ["trout", "sumfish", "perch"],
    "amphibians": ["frogs", "salamanders", "snakes", "turtles"]
}

for n, value in enumerate(pond_animals["amphibians"]):
    pond_animals["amphibians"][n] = value.title()

print(pond_animals["amphibians"])
Output:
['Frogs', 'Salamanders', 'Snakes', 'Turtles']
(Oct-27-2020, 04:30 PM)Larz60+ Wrote: [ -> ]You have lists for dictionary values, so must access each element in "grocery" and save back as value.title()
example:
pond_animals = {
    "fish": ["trout", "sumfish", "perch"],
    "amphibians": ["frogs", "salamanders", "snakes", "turtles"]
}

for n, value in enumerate(pond_animals["amphibians"]):
    pond_animals["amphibians"][n] = value.title()

print(pond_animals["amphibians"])
Output:
['Frogs', 'Salamanders', 'Snakes', 'Turtles']

Thank you for that! It was exactly what I was looking for!