如何基于具有重复键值对的数据帧行向python字典中的键追加值

如何基于具有重复键值对的数据帧行向python字典中的键追加值,python,dictionary,Python,Dictionary,我有电子商务数据,其中有一行键值对,如: row1: "ideal for":"women", "color":"blue" row2: "ideal for": "women", "color":"red" row3: "ideal for": "men", "color":"blue" 我需要的是创建一个新字典,其中包括相关值的键和数组,例如: {"ideal for": ["women","men"], "color": ["red", "blue"]} 当我尝试在新字典中向键添加值时

我有电子商务数据,其中有一行键值对,如:

row1: "ideal for":"women", "color":"blue"
row2: "ideal for": "women", "color":"red"
row3: "ideal for": "men", "color":"blue"
我需要的是创建一个新字典,其中包括相关值的键和数组,例如:

{"ideal for": ["women","men"], "color": ["red", "blue"]}
当我尝试在新字典中向键添加值时,我似乎无法找到这样做的方式,以使值不会重复

df.apply(lambda row: prep_text(row['product_specifications']), axis=1)
tag_info = df['product_specifications']
tag_info.replace('', np.nan, inplace=True)
tag_info.dropna(inplace=True)
tags_dict = dict()
for row in tag_info:
     for key, value in row.items():
         if key not in tags_dict:
             tags_dict[key] = [value]
         elif value not in tags_dict.values():
             tags_dict[key].append(value)
现在,我得到了一本新字典,看起来像这样:

{"ideal for": ["women","women","men"], "color":["blue", "red", "blue"]}

我必须怎么做才能使值不重复?

标记的元素。值是字符串列表,而不是字符串。你应该检查一下

 elif value not in tags_dict[key]:
     tags_dict[key].append(value)
或者您可以使用Set而不是List作为标记dict的值。Set只能包含每个值的一个副本,因此如果添加相同值的第二个副本,它将忽略它。但集合中的值是无序的

  if key not in tags_dict:
      tags_dict[key] = {value}
  else:
      tags_dict[key].add(value)

上面的不是有效的字典,在字典中键映射到值。您的第一个代码块是什么?我得到的字典将键映射到值,这些值是项目列表。我更正了上面的代码。@timgeb我现在添加了它为什么不在elif语句中使用if语句呢?嵌套的if语句将检查该值是否已在列表中;如果是,那么您就不会附加到列表中。否则,你附加。谢谢你,这为我澄清了它完美。