简体   繁体   English

Python:将列表转换成字典

[英]Python: converting list to dictionary

I have a list stored in a variable and I am trying to convert this list into a dictionary with with dictionary keys corresponding to their respective list index. 我有一个存储在变量中的列表,我试图将此列表转换为带有对应于其各自列表索引的字典键的字典。 The point is to create a list of images and rects to blit (which isn't shown here but I've tested that that portion of the code does indeed work). 关键是要创建图像列表和矩形框(此处未显示,但我已经测试了那部分代码确实起作用)。 Here's the code: 这是代码:

hand = ['Lakers_01.png', 'Lakers_02.png', 'Lakers_03.png', 'Lakers_04.png']
tempHand = hand
finTempHand = {}
newTempHand = ["pygame.image.load("+tempHand+")" for t in tempHand]
print(newTempHand)
for i in range(0,len(newTempHand)):
    finTempHand[i] = newTempHand[i]

and I am getting this error: 我收到此错误:

newTempHand = ["pygame.image.load("+tempHand+")" for t in tempHand]
TypeError: must be str, not list

Thank you in advance 先感谢您

You can accomplish that using dictionary comprehension. 您可以使用字典理解来实现。

hand = ['Lakers_01.png', 'Lakers_02.png', 'Lakers_03.png', 'Lakers_04.png']
finTempHand = {
    i: "pygame.image.load({})".format(x) 
        for i, x in enumerate(hand)
}

First of all you are using the wrong variable 首先,您使用了错误的变量

newTempHand = ["pygame.image.load("+tempHand+")" for t in tempHand]

should be 应该

newTempHand = ["pygame.image.load("+t+")" for t in tempHand]

Second you can use a dict comprehension and also remove that 0 from the range 其次,您可以使用dict理解,也可以从范围中删除该0

Full code: 完整代码:

    hand = ['Lakers_01.png', 'Lakers_02.png', 'Lakers_03.png', 'Lakers_04.png']

    finTempHand = {
        i: 'pygame.image.load({})'.format(current)
        for index, current in enumerate(hand)
    }

Final result inspired in @Rhaul 's answer bellow 最终结果受到@Rhaul的回答启发

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM