If I have a list for example :
courses = [{name: a, course: math, count:1}]
and if I input again name: a course: math the list will be
courses = {name: a, course: math, count:2}
I just want the item with the same name and course will not append to the list but only increasing 'count' key item.
I tried :
def add_class(inputname,inputcourse):
for i in (len(courses)):
if courses[i]['name']== inputname and courses[i]['course']==inputcourse:
courses[i][count]+=1
else :
newdata = {"name":inputname, "course":inputcourse,count:1}
#i put count because this item is the first time.
courses.append(newdata)
print courses
I expect the output is class = {name: a, course: math, count:2}
but the actual output is class = [{name: a, course: math, count:2},{name: a, course: math, count:1}]
if i input a new data like name : a, course: physic the output will be
[{name:a,course:physic,count:1},{name: a, course: math, count:2},{name: a, course: math, count:1}]
May I suggest you a different approach?
Instead of using a list of dictionaries wich may be complicated to manage in your case, write your own class to store "name" and "course".
By defining the special method
__hash__
and__eq__
you make your objects hashable, so they can be counted by Counter. If you write something like this:the
print
will gives youCounter({[a: math]: 2, [b: physics]: 1})
With this approach, you may just append all the
NC
objects to your list and at the end use Counter to get the repetitions.EDIT after request in the comment.
To do the same thing in "real time" you can create an empty counter an then update it.
Just remember that
Counter.update
wants an iterable, so if you want to add one element to the Counter, you have to give in input a list with that one element. Of course you may also add more elements togheter, for example:lc.update([NC("b", "physics"), NC("c", "chemistry")])
is valid and both objects are added to the counter.You can use a for else clause. The else part will be called only if break is not reached, here is an example for you
As an output you have
[{'name': 'a', 'course': 'math', 'count': 2}, {'name': 'a', 'course': 'english', 'count': 1}]