繁体   English   中英

Python - 如何在字典中使用 append 个变量

[英]Python - How to append variables in a dict

我对此有点陌生。 我正在使用for 循环从 .csv 文件中获取 ID,并将该数据存储到一个变量中。 在 for 循环中,有条件执行一些“网络抓取”(我只需要从网站上知道该 ID 的值)。 然后是有条件的,我会说类似的话

for u in df['ID']: 

    url = f"example.com/{u}" 
    response = requests.get(url)
    html = BeautifulSoup(response.text, 'html.parser')
    finder = html.find("something about BeautifulSoup library")
    my_variable = finder.get_text()

    if "hello world" in my_variable:
        final_variable = "hello world"
    elif "hi world" in my_variable:
        final_variable = "hi world"
    else:
        pass

这部分代码效果很好。 当我尝试将该数据存储到字典中时,坏事就开始了。

对于我所做的事情:

dictionary = {}
dictionary[f'{u}'] = risk

但后来意识到我是多么愚蠢,而这个命令只是在重写自己。

我也尝试做一个 append 但我无法将它用于键和值。

键应该是.csv中的ID(或者代码中的“u”),值必须是final_variable。

我认为正确的做法是添加一个 append,但我不知道该怎么做。

谢谢!

扩展一下我的评论——使用dictionary[key] = value是添加到字典的正确方法,但是如果你想为每个循环迭代执行一次,那么你必须在循环之外初始化它。 请参阅下面的完整示例(如果是设计的)。

# Initialise an empty dictionary
my_dict = {}

for i, letter in enumerate("abcde"):
    # Maybe some HTML parsing...

    # Add a new mapping to the dictionary each loop iteration
    my_dict[letter] = i

print(my_dict)  # {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4}

另请注意, f'{u}'可能是不必要的 - 根据您的需要,您可能只使用u本身作为字典键。 如果您确实需要将其转换为字符串,则单个值的惯用方式是str(u)

暂无
暂无

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

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