Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating a dictionary with upper case values of the keys already present in the dictionary

Tags:

python

I have a dict variable d containing character-character key value pair. All these characters are in smaller case. I want to store the corresponding upper case character mapping as key value pairs too.

The dictionary consists of these entries

d[q]='a'
d[w]='s'
d[e]='d'
d[r]='f'
d[t]='g'

I want to have this also

d[Q]='A'
d[W]='S'
d[E]='D'
d[R]='F'
d[T]='G'

How can I do this ?

like image 204
OneMoreError Avatar asked Nov 29 '25 16:11

OneMoreError


1 Answers

Use a generator expression to update your dictionary:

d.update({k.upper(): v.upper() for k, v in d.iteritems()})

or, for Python 3:

d.update({k.upper(): v.upper() for k, v in d.items()})

or, for Python 2.6 and earlier:

d.update([(k.upper(), v.upper()) for k, v in d.iteritems()])

This loops over all key-value pairs in d then adds a corresponding uppercase key-value pair.

like image 174
Martijn Pieters Avatar answered Dec 02 '25 06:12

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!