Python3:遍历字典中的列表?

时间:2021-02-01 20:46:00

标签: python python-3.x list loops dictionary

我有一个字典,其中每个值都是一个列表。我的目标是使用字典中找到的字符替换来生成单词“cat”的所有可能变体(我失败得很惨):

#!/usr/bin/python3

import sys

user_input = "cat"

dictionary = {
"c": ["c","C"],
"a": ["a","A","@"],
"t": ["t","T"]}

word = ""

for char in user_input:
    if char in dictionary:
        for i in dictionary[char]:
            word += i
    else:
        word += char

print(word, end="")

当前输出:

cCaA@tT

所需的输出:

cat
caT
cAt
cAT
c@t
c@T
Cat
CaT
CAt
CAT
C@t
C@T

如何遍历每个列表以生成所需的输出?任何建议或建议都会有所帮助,我还是 Python 新手。

0 个答案:

没有答案