循环时更新 pandas 字典 Python

Updating pandas Dictionary Python while looping

我正在尝试在 python:

中实现 dash component - dropdown menu

根据dash:

我的 option 参数需要遵循此模式:

options=[
    {'label': 'New York City', 'value': 'NYC'},
    {'label': 'Montréal', 'value': 'MTL'},
    {'label': 'San Francisco', 'value': 'SF'}
],
value='MTL')  

我有兴趣在我的 pandas dataframe 中使用带有公司名称的 column 作为 dropdown

所以我意识到我可以利用 python dictionaries:

mydict = {}
option = []

for comp in df.company:
    mydict["label"] = comp 
    mydict["value"] = comp 
    option.append(mydict)

printing option 结果符合我的预期,但公司名称列中只有第一个 company。它一直重复着这一切。我的操作有什么问题?

您遇到的问题是 python 仅列出商店 references。由于您只有一本字典,因此列表中的所有元素(引用)都将指向同一本字典。您必须为每个选项创建一个新字典:

option = []

for comp in df.company:
    mydict = {}
    mydict["label"] = comp 
    mydict["value"] = comp 
    option.append(mydict)

我喜欢为此使用单线:

options = [{"label":x, "value":x} for x in df.company]