【问题标题】:Add item to a list of dictionaries if item is in different list python如果项目在不同的列表python中,则将项目添加到字典列表中
【发布时间】:2021-07-02 09:16:20
【问题描述】:

我没有一个很好的方法来解释它,但我可以尽力帮助想象我正在尝试做的事情。

我有一个清单:

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] }

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

【问题讨论】:

  • 我认为基本 python 库中已经实现了这个解决方案。您是否已经尝试过自己为这个问题实施解决方案?如果是这样,你的方法是什么,你在努力解决什么问题?

标签: python list dictionary append


【解决方案1】:

这可能是最短的方法:

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' 开头。

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

【讨论】:

    【解决方案2】:

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

    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)
    

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

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

    【讨论】:

    • 谢谢!这也正是我想要的方式! :)
    【解决方案3】:

    试试这个:

    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)
    

    【讨论】:

      猜你喜欢
      • 2013-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-12
      • 1970-01-01
      • 2021-07-11
      相关资源
      最近更新 更多