(PYTHON)遍历字典

2024-10-04 09:26:33 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有两本字典:

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

我希望我的“for循环”遍历字典,用“corlets”键替换“random letters”键,并输出到字符串。到目前为止,我是这样做的:

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循环进行迭代并将其作为字符串输出到终端吗


Tags: 字符串infor字典randomkeysreplacevalues
1条回答
网友
1楼 · 发布于 2024-10-04 09:26:33

如果您只想知道输出:

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)

The output is: the

但是,如果还要更改随机字母上的键,请执行以下操作:

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 output is: "the" and the randomLetter dictionary is "{'t': 0, 'h': 1, 'e': 2}"

希望有帮助,祝你有一个愉快的一天

大卫

相关问题 更多 >