sln
sln

Reputation: 159

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

Upvotes: 5

Views: 731

Answers (3)

PMende
PMende

Reputation: 5460

IIUC: You can do this as follows,

string_dict = {
    char: char.upper() if char == char.lower() else char.lower()
    for char in (string.lower() + string.upper())
}

Upvotes: 0

mad_
mad_

Reputation: 8273

Another way to do the same

import string
d=dict(zip(string.ascii_lowercase[:3],string.ascii_uppercase[:3]))
d.update(dict(zip(string.ascii_uppercase[:3],string.ascii_lowercase[:3])))

Upvotes: 0

Dani Mesejo
Dani Mesejo

Reputation: 61920

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

Upvotes: 9

Related Questions