Home > Enterprise >  How to capitalize the first letter in dict values only
How to capitalize the first letter in dict values only

Time:12-02

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.

CodePudding user response:

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()

CodePudding user response:

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']}

CodePudding user response:

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']}

  • Related