Python 从字典中追加新列表

Python 从字典中追加新列表,python,list,loops,dictionary,Python,List,Loops,Dictionary,我希望从下面的代码中将颜色(在新列表中)链接到特定值,例如:如果值为a或a,则颜色应始终为红色,图案填充应为“”。 我尝试了以下代码,它工作正常,但当我激活“else:”向列表添加新值时,它会返回一个长的混合列表 有人能帮我吗 非常感谢 dict1= {"A": ["red","."],"B": ["green","//"],"C": ["blue","o"],"D": ["Yellow","|"]} name = ["g","B","c","d","a"] color =[] hatch=[]

我希望从下面的代码中将颜色(在新列表中)链接到特定值,例如:如果值为a或a,则颜色应始终为红色,图案填充应为“”。 我尝试了以下代码,它工作正常,但当我激活“else:”向列表添加新值时,它会返回一个长的混合列表

有人能帮我吗

非常感谢

dict1= {"A": ["red","."],"B": ["green","//"],"C": ["blue","o"],"D": ["Yellow","|"]}
name = ["g","B","c","d","a"]
color =[]
hatch=[]

for i in range(len(name)):
    for key, value in dict1.items():
        if name[i].upper() == key:
            name[i]=name[i].upper()
            color.append(value[0])
            hatch.append(value[1])
        # else:
        #     color.insert(i,"white")
        #     hatch.insert(i,"x")

print(name) # ['g', 'B', 'C', 'D', 'A']
print(color) # ['white','green', 'blue', 'Yellow', 'red']
print(hatch) # ['x','//', 'o', '|', '.']

您使用了一个不必要的循环来遍历导致主要问题的字典

以下代码起作用:

dict1 = {"A": ["red", "."], "B": ["green", "//"], "C": ["blue", "o"], "D": ["Yellow", "|"]}
name = ["g", "B", "c", "d", "a"]
color = []
hatch = []

for i in range(len(name)):
    if name[i].upper() in dict1:
        key = name[i].upper()
        color.append(dict1[key][0])
        hatch.append(dict1[key][1])
    else:
        color.insert(i, "white")
        hatch.insert(i, "x")

print(name)  # ['g', 'B', 'C', 'D', 'A']
print(color)  # ['white','green', 'blue', 'Yellow', 'red']
print(hatch)  # ['x','//', 'o', '|', '.']