djangodjames
djangodjames

Reputation: 319

Python dictionary update doesn't work inside for loop

I have a method get_h1() that returns 2 tags:

[<h2>Запись к врачу</h2>, <h2>Запись на диагностику</h2>]

I have another method that has a for loop inside. It should get both tags from the get_h1() method and add 3 values in dictionary. But in result it returns values only for 1 tag

def print_h1(self):
        self.h1 = {}
        self.h1_all = self.get_h1()
        self.h1_all = [self.h.text for self.h in self.h1_all]
        for self.h in self.h1_all:
            self.value = self.h
            self.leng = len(self.h)
            if self.key in self.h:
                self.key = "YES"
            else: 
                self.key = "NO"
            self.h1.update({'value':self.value, 'leng': self.leng, 'key': self.key})
        return self.h1

Here is the result:

{'value': 'Запись на диагностику', 'leng': 21, 'key': 'NO'}

How can I get the result for both tags?

Upvotes: 0

Views: 580

Answers (1)

ForceBru
ForceBru

Reputation: 44828

From the documentation:

dict.update([other])

Update the dictionary with the key/value pairs from other, overwriting existing keys.

You have one self.h1 dictionary, and each call to self.h1.update overwrites its data. Moreover, it's impossible to put duplicate keys into dictionaries.

If you want to store data about multiple H1 tags, you should use a list of dictionaries.

Upvotes: 1

Related Questions