从字符串创建一个字典,每个字符都是键和值

sln*_*sln 5 python python-3.x

对于我来说,从字符串创建字典的最佳方法是什么,键是每个字符,其大写和值是相反的情况?我可以使用两行词典全面但更好的方法吗?例如:

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

string = 'abc'
d = { i:i.upper() for i in string}
d.update({ i.upper():i for i in string})
Run Code Online (Sandbox Code Playgroud)

Dan*_*ejo 10

使用swapcase:

s = 'abc'

result = dict(zip(s + s.swapcase(), s.swapcase() + s))
print(result)
Run Code Online (Sandbox Code Playgroud)

产量

{'C': 'c', 'b': 'B', 'B': 'b', 'a': 'A', 'A': 'a', 'c': 'C'}
Run Code Online (Sandbox Code Playgroud)

  • 这是非常可读的,并且意图非常明确. (3认同)