Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将列表导入到字典值Python中_Python_List_Dictionary - Fatal编程技术网

将列表导入到字典值Python中

将列表导入到字典值Python中,python,list,dictionary,Python,List,Dictionary,我正在尝试从主功能导入此列表项: character1 = Character("Conan the Barbarian") for test_item in ["sword", "sausage", "plate armor", "sausage", "sausage"]: character1.give_item(test_item) 我正在使用类,在类中有这

我正在尝试从主功能导入此列表项:

character1 = Character("Conan the Barbarian")


for test_item in ["sword", "sausage", "plate armor", "sausage", "sausage"]:
    character1.give_item(test_item)
我正在使用类,在类中有这些方法将列表保存到角色

class Character:

    def __init__(self, character):

        self.__character = character
        self.__dct = {}

    def give_item(self, items):

        self.__dct[self.__character] = items


    def printout(self):

        for characters in self.__dct:
            print(f'Name:', characters)
            for items in self.__dct.keys():
                print(self.__dct[self.__character])
我的输出仅打印列表中的最后一个条目,看起来这些条目被覆盖了。但我真的不明白为什么

我的输出

Name: Conan the Barbarian
sausage
我希望我的输出是:


Name: Conan the Barbarian
   plate armor
   sausage
   sword

这是因为您正在重复使用密钥。每次,您都将分配给
self.\uu dict[self.\uuu character]

self.\u dict.keys())中项目的循环写得很奇怪
items
这里实际上是一个键列表,因此只会运行一次,而实际上您希望运行它#items次

相反,您可以使用列表(或集合):

def\uuuuu init\uuuuuuu(自我,字符):
self.\uu character=字符
self.\uu dct={}
self.\u dct[self.\u字符]=[]
def打印输出(自):
对于self.\u dct中的字符:
打印(f'Name:',字符)
对于self.\u dct[self.\u字符]中的项目:
打印(项目)

这是因为您正在重复使用密钥。每次,您都将分配给
self.\uu dict[self.\uuu character]

self.\u dict.keys())中项目的循环写得很奇怪
items
这里实际上是一个键列表,因此只会运行一次,而实际上您希望运行它#items次

相反,您可以使用列表(或集合):

def\uuuuu init\uuuuuuu(自我,字符):
self.\uu character=字符
self.\uu dct={}
self.\u dct[self.\u字符]=[]
def打印输出(自):
对于self.\u dct中的字符:
打印(f'Name:',字符)
对于self.\u dct[self.\u字符]中的项目:
打印(项目)

看起来像是您的
self.\uu dct[self.\uuu character]=items
行使用
[self.\uuuu character]
作为要附加到dict的键。在Python字典中,您可以简单地添加列表,只需编写键并将列表作为值,如下所示:

self.__dct = {
    "name" = character_name,
    "items" = list_of_items
}

它看起来像是您的
self.\uu dct[self.\uuuu character]=items
行使用
[self.\uuuu character]
作为要附加到您的dict的键。在Python字典中,您可以简单地添加列表,就像编写键并将列表作为值一样:

self.__dct = {
    "name" = character_name,
    "items" = list_of_items
}

为什么您要使用
dict
来存储项目序列,而不是例如
列表
?为什么您要使用
dict
来存储项目序列,而不是例如
列表
?谢谢您,问题解决了,出于某种原因,我认为主循环正在遍历列表中的每个元素,并将其作为单个字符串导入,而不是一次导入整个列表:)谢谢你,解决了它,出于某种原因,我认为主循环正在列表中的每个元素中运行,并将其作为单个字符串导入,而不是一次导入整个列表:)非常感谢分享这一点,我试图使用字符名是dct键,而项目列表作为键值。但是仍然感谢分享:)非常感谢分享,我试着用字符名作为dct键,用项目列表作为键值。但还是要感谢你分享这个:)