如果项目在不同的列表中,则将项目添加到词典列表 python

Add item to a list of dictionaries if item is in different list python

我没有很好的方式来解释它,但我会尽力帮助形象化我正在尝试做的事情。

我有一个列表:

post1_tags = ['Tag1', 'Tag2']

我也有一个类似的列表。

post2_tags = ['Tag1']

基本上,如果第一个列表有标签,则将其添加到以标签名称为键的列表字典中。 因为 post1_tags 有标签 'Tag1''Tag2',所以应该像这样添加到字典中:

tags = {'Tag1': [post1_tags], 'Tag2': [post1_tags]}

但如果只是 post2_tags,那么它应该变成:

tags = {'Tag1': [post2_tags]}

我希望能够将列表放在一个字典中,它们的键是标签,如果它们有那个标签,就添加它。

我希望最终结果看起来像这样:

tags = {'Tag1': [post1_tags, post2_tags], 'Tag2': [post_1_tags] }

我希望这是有道理的。如果不是请告诉我,以便我澄清。

我不清楚你是想要字典中列表的内容还是名称,但这里有一个解决方案:

post1_tags = ['Tag1', 'Tag2']
post2_tags = ['Tag1']
tags = dict()

#Making the dictionary just out of the first list
for tag in post1_tags:
    tags[tag] = ["post1_tags"]

for tag in post2_tags:
    if tag in tags.keys():      #Checking if the tags are already in the dict
        tags[tag].append("post2_tags")
    else:    #Adding the remaining to the dict
        tags[tag] = ["post2_tags"]

print(tags)

如果您想要列表名称的内容,只需删除列表名称周围的 "

如果您不需要列表的变量名,您也可以遍历列表的列表(就像在第二个 for 循环中,但包含在另一个循环中)。

试试这个:

list1 = ["Tag1", "Tag2"]
list2 = ["Tag1"]
lists = {"list1": list1 , "list2": list2}
dictionary = {}
for key, value in lists.items():
    for tag in value:
        try:
            if dictionary[tag]:
               dictionary[tag] += f" {key}"
        except KeyError:
            dictionary[tag] = key
        
print(dictionary)

这可能是最短的方法:

tags = {}

for i in post1_tags + post2_tags:
    tags[i] = [n for n,v in filter(lambda t: isinstance(t[1],list) and t[0].startswith('post'), locals().items()) if i in v]

print(tags)

我觉得除了第 4 行之外的大部分代码都是可以解释的。第 7 行所做的是首先获取一个包含特定标签并以 'post'.[=15 开头的每个变量的列表=]

此代码的唯一缺点是使用了 local 变量。 localglobal 变量是会弄乱代码的项目。如果您的代码很短,那么这是完美的。但是,如果您的代码很长,那么我建议将代码放入一个函数中以保持代码整洁。