Alsakka
Alsakka

Reputation: 185

import a list into a dictionary value Python

I am trying to import this list item from the main function:

character1 = Character("Conan the Barbarian")


for test_item in ["sword", "sausage", "plate armor", "sausage", "sausage"]:
    character1.give_item(test_item)

I am using class and in the class there is those methods to save the list to the character

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])

my output is printing only the last entry from the list, seems like the entries being overwritten. But I can't really figure why.

my output

Name: Conan the Barbarian
sausage

I want my output to be:


Name: Conan the Barbarian
   plate armor
   sausage
   sword

Upvotes: 0

Views: 364

Answers (2)

J-Dumas
J-Dumas

Reputation: 89

It seems like your self.__dct[self.__character] = items line uses the [self.__character] as the key to append to your dict. In a Python Dictionnary, you can just add your list as easy as writing the key and putting the list as the value like so:

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

Upvotes: 0

M Z
M Z

Reputation: 4799

This is because you're reusing your key. Every time, you assign to self.__dict[self.__character]

Your loop for items in self.__dict.keys()) is oddly written. items here is actually a list of keys, and will therefore only run once, when in actuality you want to run it # items times.

Instead, you could use a list (or set):

def __init__(self, character):

    self.__character = character
    self.__dct = {}
    self.__dct[self.__character] = []

def printout(self):
    for characters in self.__dct:
        print(f'Name:', characters)
            for item in self.__dct[self.__character]:
                print(item)

Upvotes: 2

Related Questions