newbzzs
newbzzs

Reputation: 315

How to capitalize the first letter in dict values only

Here is a dictionary

dictionary = {'Happy':['SMILE','LAUGH','BEAMING'],
              'Sad':['FROWN','CRY','TEARS'],
              'Indifferent':['NEUTRAL','BLAND', 'MEH']}

I am trying to change the values in the entire dictionary such that SMILE becomes Smile, LAUGH becomes Laugh etc.

This is what I'm attempted

{str(k).upper():str(v).upper() for k,v in dictionary.values()}

But the result of this is capitalizing the keys and does noting to the values.

Upvotes: 1

Views: 2006

Answers (3)

user17562336
user17562336

Reputation:

One solution:

result = {k: [emotion[0].upper() + emotion[1:].lower() for emotion in v] for k, v in dictionary.items()}

Then result is

{'Happy': ['Smile', 'Laugh', 'Beaming'], 'Sad': ['Frown', 'Cry', 'Tears'], 'Indifferent': ['Neutral', 'Bland', 'Meh']}

Upvotes: 1

balderman
balderman

Reputation: 23825

Try the below

d = {'Happy':['SMILE','LAUGH','BEAMING'],
              'Sad':['FROWN','CRY','TEARS'],
              'Indifferent':['NEUTRAL','BLAND', 'MEH']}
d = {k:[x.capitalize() for x in v] for k,v in d.items()}
print(d)

output

{'Happy': ['Smile', 'Laugh', 'Beaming'], 'Sad': ['Frown', 'Cry', 'Tears'], 'Indifferent': ['Neutral', 'Bland', 'Meh']}

Upvotes: 2

mozway
mozway

Reputation: 262164

You can use:

{k.upper():[s.capitalize() for s in v]
 for k,v in dictionary.items()}

output:

{'HAPPY': ['Smile', 'Laugh', 'Beaming'],
 'SAD': ['Frown', 'Cry', 'Tears'],
 'INDIFFERENT': ['Neutral', 'Bland', 'Meh']}

NB. this is also changing the key to capitals, I'm not sure if this is what you wanted. If not use k or k.capitalize()

Upvotes: 3

Related Questions