Python Forum
How to capitalize in dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to capitalize in dictionary
#1
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
Larz60+ write Oct-27-2020, 04:18 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.

Fixed for you this time
Reply
#2
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']
Inkanus likes this post
Reply
#3
(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!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Find and replace to capitalize with Regex hermobot 2 2,483 Mar-21-2020, 12:30 PM
Last Post: hermobot
  [split] capitalize dict keys for display in string newbieAuggie2019 3 2,939 Oct-10-2019, 10:50 AM
Last Post: perfringo
  Python capitalize() method problem Skipper 9 10,512 Jan-27-2018, 03:11 PM
Last Post: Skipper

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020