(PYTHON)遍历字典

时间:2020-09-08 15:05:51

标签: python for-loop

说我有两个字典:

randomLetters = {'j': 0, 'p': 1, 'x': 2}
corLetters = {'t': 0, 'h': 1, 'e': 2}

我希望我的“ for循环”遍历字典,并用“ corLetters”键替换“随机字母”键并输出到字符串。到目前为止,这就是我的想法:

for k in randomLetters.values():
    attempt = strOne.replace(randomLetters.keys()[k], corLetters.keys()[k]) 
print("\nThe first attempt at deciphering is: ")
print(attempt)

当我将其打印出来时,我期望输出是“ the”,但是我却得到了“ jpe”。有人可以告诉我如何使用for循环正确地迭代并将其作为字符串输出到终端吗?

1 个答案:

答案 0 :(得分:0)

如果您只想知道输出,则

randomLetters = {'j': 0, 'p': 1, 'x': 2}
corLetters = {'t': 0, 'h': 1, 'e': 2}
attempt=" "
for h,k in randomLetters.items():
        for i,x in corLetters.items():
            if k==x:
                attempt=attempt+i

print("\nThe first attempt at deciphering is: "+attempt)

输出为:

但是,如果您还想更改randomLetters上的密钥:

randomLetters = {'j': 0, 'p': 1, 'x': 2}
corLetters = {'t': 0, 'h': 1, 'e': 2}
attempt=" "
for h,k in randomLetters.items():
        for i,x in corLetters.items():
            if k==x:
                randomLetters[i] = randomLetters.pop(h)
                attempt=attempt+i

print("\nThe first attempt at deciphering is: "+attempt)

输出为:“ the”,randomLetter词典为“ {'t':0,'h':1,'e':2}”

希望对您有帮助,祝您有愉快的一天,

大卫