【发布时间】:2020-10-15 07:28:40
【问题描述】:
我想创建简单的“编码脚本”。
我有这本词典:
diction = {
"A" : "Z",
"Y" : "B",
"C" : "X"
}
我想给出一些随机句子,遍历它的字母,如果在这本词典中找到字母 - 打印相反的字母
所以,如果我说的话
"ABC"
它应该返回:
"ZYX"
我试过这段代码,但我有一个“KeyError”:
# Defining dictionary
diction = {
"A" : "Z",
"Y" : "B",
"C" : "X",
"W" : "E",
"E" : "V",
"U" : "F",
"G" : "T",
"S" : "H",
"I" : "R",
"Q" : "J",
"K" : "P",
"O" : "L",
"M" : "N",
" " : " "
}
# Sentence in "szyfr" variable should be split into list.
szyfr = "SOME SENTENCE WHATEVER"
def split(szyfr):
return [char for char in szyfr]
szyfr = split(szyfr)
# Now I want to iterate through "szyfr" and replace letters as in "CAT" example:
for i in szyfr:
if i in diction:
diction = {x:y for x,y in diction.items()}
print(i)
print("Variable: " + i + " is in 'key'")
pass
elif diction[i] in szyfr:
diction = {y:x for x,y in diction.items()}
print(i)
print("Variable: " + i + " is in 'value'")
elif i is " ":
pass
print(szyfr)
【问题讨论】:
-
你为什么在你的循环中改变
diction?
标签: python python-3.x dictionary if-statement