user13047041
user13047041

Reputation: 55

Convert a list of values for a specific key to upper case in dictionary

I want to convert names only in 'team2' to uppercase.

team = {'team1': ['Anne', 'Tom'],
        'team2': ['Jane', 'Mark'],
        'team3': ['Gaby', 'Alex']}

My script:

for k in team.keys():
    if k == 'team2':
        for v in enumerate(team.values()):
           team.values[index] = values.upper()
print(team)

It doesn't work. Can anyone please help? Truly appreciated your help.

Upvotes: 0

Views: 395

Answers (2)

Rima
Rima

Reputation: 1455

Below code converts the key & value into string so that upeer method can be applied.

team = {'team1': ['Anne', 'Tom'],
        'team2': ['Jane', 'Mark'],
        'team3': ['Gaby', 'Alex']}

dict_team={str(k):str(v).upper() if k=='team2' else v for k,v in team.items()}

print(dict_team)

output

{'team1': ['Anne', 'Tom'], 'team2': "['JANE', 'MARK']", 'team3': ['Gaby', 'Alex']}

Upvotes: 0

Samwise
Samwise

Reputation: 71444

Since team is a dictionary, you can simply access team['team2'] directly instead of having to iterate over each element:

>>> team['team2'] = [name.upper() for name in team['team2']]
>>> team
{'team1': ['Anne', 'Tom'], 'team2': ['JANE', 'MARK'], 'team3': ['Gaby', 'Alex']}

Upvotes: 1

Related Questions