Home > Enterprise >  appending only first object
appending only first object

Time:09-27

guys idk why my dict appending only first item from list,and i dont have any ideas for that



class Nums:

    def __init__(self, lst_nums: list, dict_nums: dict):
        self.lst = lst_nums
        self.dict_nums = dict_nums
        self.dict_nums = {}

    def changer(self):

        self.dict_nums = {"": ""}
        for i in self.lst:
            if i in self.lst:
                self.dict_nums = {i: i}
            return self.dict_nums


f = Nums(lst_nums=[1, 4, 5, 6, 7], dict_nums={})

with open('number.txt', 'w') as number:
    number.write(json.dumps(str(f.changer())))

CodePudding user response:

As someone pointed out in the comments self.dict_nums = {i: i} creates a new dictionary with a single key/value pair. Not only that, but you're returning after the first execution of the loop. The if statement is also redundant since every element will be in the list(since you're looping over the list)

def changer(self):

    self.dict_nums = {"": ""}
    for i in self.lst:
        self.dict_nums[i] = i
    return self.dict_nums

CodePudding user response:

To start when you return the return self.dict_nums you are not letting the for loop process in its entirety.

Second, itering your list twice will not be helpful here unless you are attempting to multiply or add the numbers together or something.

class Nums:

def __init__(self, lst_nums: list, dict_nums: dict):
    self.lst = lst_nums
    self.dict_nums = dict_nums
    self.dict_nums = {}

def changer(self):
    for i in self.lst:
        self.dict_nums[i] = i
    return self.dict_nums


f = Nums(lst_nums=[1, 4, 5, 6, 7], dict_nums={})

with open('number.txt', 'w') as number:
    number.write(json.dumps(str(f.changer())))

Which produces

"{'': '', 1: 1, 4: 4, 5: 5, 6: 6, 7: 7}"

CodePudding user response:

In __init__() you initialize an empty dict (good) with self.dict_nums = {} but in change() you then overwrite it (twice). You probably want to just modify it like this instead:

    def changer(self):
        for i in self.lst:
             self.dict_nums[i] = i
        return self.dict_nums
  • Related