1

How to append dictionaries(returning from method of a class) to a list, without getting previous dictionaries overwritten by latest dictionary in python

Lets say I have following classes

class Student:
    details_dict = {'name':'', 'age':0}

class FillDetails(Student):
    def get_details(self, name, age):
        self.details_dict['name'] = name
        self.details_dict['age'] = age
        return self.details_dict

I am creating an instance of FillDetails() class

obj = FillDetails()

And calling method get_details() which returns a dictionary

info_dict = obj.get_details('Panda',13)
print(info_dict)
print(type(info_dict))
Output: {'age': 13, 'name': 'Panda'}
        dict

Then I am saving info_dict to a list

info_lst = []
info_lst.append(info_dict)
info_lst
Output:[{'age': 13, 'name': 'Panda'}]

Now, when I am calling the method get_details() again with new values and appending it to the list as follows

info_dict = obj.get_details('Tortoise',14)
info_lst.append(info_dict)
info_lst
Output: [{'age': 14, 'name': 'Tortoise'}, {'age': 14, 'name': 'Tortoise'}]

The previous dictionary got overwritten by new dictionary. How can I append dictionaries without getting over-written into a list? And also please help me understanding why it is happening, as I am saving dictionary to a variable and appending it.

Abdul Quddus
  • 111
  • 2
  • 10
  • 1
    May be you should check the difference between a **class variable** and an **instance variable**. – Abdul Niyas P M Oct 29 '18 at 07:32
  • `details_dict` is class variable here which is shared among all instances. Even though you modified it for only for one instance, since it is a class variable it will affect all other instances. – Abdul Niyas P M Oct 29 '18 at 07:37
  • Good point, but even when I changed the class variable to instance variable like def __init__(self): self.details_dict = {'name':'', 'age':0} still facing the same issue – Abdul Quddus Oct 29 '18 at 07:40
  • Got Answer from the referred question by @Aran-Frey, I should return copy of the dictionary as self.details_dict.copy() Thanks for helping – Abdul Quddus Oct 29 '18 at 08:43

0 Answers0