Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a dictionary from string that each character is key and value

What is the best way for me to create a dictionary from a string that key is each character and its upper case and value is its opposite case? I can use two line dictionary comprehensive but any better way? ex:

string: abc => {'a': 'A', 'b': 'B', 'c': 'C', 'C': 'c', 'B': 'b', 'A': 'a'}

string = 'abc'
d = { i:i.upper() for i in string}
d.update({ i.upper():i for i in string})
like image 896
sln Avatar asked Jan 18 '19 19:01

sln


1 Answers

Use swapcase:

s = 'abc'

result = dict(zip(s + s.swapcase(), s.swapcase() + s))
print(result)

Output

{'C': 'c', 'b': 'B', 'B': 'b', 'a': 'A', 'A': 'a', 'c': 'C'}
like image 93
Dani Mesejo Avatar answered Sep 30 '22 04:09

Dani Mesejo