简体   繁体   English

Python 字典更新在 for 循环中不起作用

[英]Python dictionary update doesn't work inside for loop

I have a method get_h1() that returns 2 tags:我有一个返回 2 个标签的方法get_h1()

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

I have another method that has a for loop inside.我有另一种方法,里面有一个 for 循环。 It should get both tags from the get_h1() method and add 3 values in dictionary.它应该从get_h1()方法中获取两个标签并在字典中添加 3 个值。 But in result it returns values only for 1 tag但结果它只返回 1 个标签的值

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?如何获得两个标签的结果?

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.你有一个self.h1字典,每次调用self.h1.update覆盖它的数据。 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 .如果要存储有关多个H1 标签的数据,则应使用字典列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM