【问题标题】:Need to remove duplicate keys without removing entire dictionary需要删除重复键而不删除整个字典
【发布时间】:2020-05-09 19:29:11
【问题描述】:

我想从字典中删除重复的键“John Doe”。

字典

info = [{"author": "John Doe", "book": {"title": "Getting started with Golang", "rating": 4.2, "category": "programming"}},
        {"author": "John Doe", "book": {"title": "Best practices with Reactjs", "rating": 4.4, "category": "front-end"}}]

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

test = {info[0]["author"]: [info[0]["book"], info[1]["book"]]}

我的尝试,除了这会删除整个第二个字典。

aList = {}
final = []

for i in info:
    for values in i.values():
        if values not in aList.values():
            aListi["author"] = values

print(aList)

我们将不胜感激!

【问题讨论】:

    标签: python python-3.x dictionary key key-value


    【解决方案1】:

    您可以使用itertools.groupby 并获取我建议使用operator.itemgetter 的密钥

    from itertools import groupby
    from operator import itemgetter
    
    info = [{"author": "John Doe", "book": {"title": "Getting started with Golang", "rating": 4.2, "category": "programming"}},
            {"author": "John Doe", "book": {"title": "Best practices with Reactjs", "rating": 4.4, "category": "front-end"}}]
    
    result = {k: [d['book'] for d in g] for k, g in groupby(info, itemgetter('author'))}
    

    {'John Doe': [{'title': 'Getting startedwith Golang', 'rating': 4.2, 'category':'programming'},
                  {'title': 'Best practices with Reactjs', 'rating': 4.4, 'category': 'front-end'}]}
    

    【讨论】:

      【解决方案2】:

      你可以试试这个:

      new_dict = pd.DataFrame(info).groupby(['author'])['book'].\
                 apply(lambda x : x.tolist()).\
                 to_dict()
      
      new_dict
      
      {'John Doe': [{'title': 'Getting started with Golang',
         'rating': 4.2,
         'category': 'programming'},
        {'title': 'Best practices with Reactjs',
         'rating': 4.4,
         'category': 'front-end'}]}
      

      【讨论】:

        【解决方案3】:

        尝试使用groupby:

        print({k: [book["book"] for book in g] for k, g in groupby(info, lambda x: x["author"])})
        

        输出:

        {'John Doe': [{'title': 'Golang 入门', 'category': 'programming', 'rating': 4.2}, {'title': '最佳实践 Reactjs','类别':'前端','评级':4.4}]}

        【讨论】:

        • 目前我正在尝试不使用有助于解决此类问题的库。我是初学者。感谢您的帮助仍然
        • 我认为你可以使用@fixatd 解决方案。
        【解决方案4】:

        这应该给你你想要的;

        info = [{"author": "John Doe", "book": {"title": "Getting started with Golang", "rating": 4.2, "category": "programming"}},
                {"author": "John Doe", "book": {"title": "Best practices with Reactjs", "rating": 4.4, "category": "front-end"}}]
        
        authors = {}
        
        for entry in info:
            authors.setdefault(entry['author'], []).append(entry['book'])
        
        print(authors)
        
        # Output
        {'John Doe': [{'title': 'Getting started with Golang', 'rating': 4.2, 'category': 'programming'}, {'title': 'Best practices with Reactjs', 'rating': 4.4, 'category': 'front-end'}]}
        

        这使用了setdefault,它只是初始化了一个特定的键,在这种情况下是你的作者姓名,append 是列表中的项目。

        【讨论】:

        • 使用setdefault 的链接对其进行了更新,但总结起来类似于get 的工作方式,但它也使用默认值填充项目。如果您发现它有帮助,可以将其标记为答案,那就太好了。谢谢!
        • 只是一个小问题,.setdefault(entry["author] 删除重复项了吗?
        • 不应该,它会检查那个键 entry['author'] 是否存在。如果它不存在,它将使用您的默认值填充,在我们的例子中为[](一个空列表),否则它只会返回entry['author'] 键下的当前值。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-01-30
        • 2019-05-10
        • 2020-11-22
        • 1970-01-01
        • 2018-02-06
        • 1970-01-01
        • 2023-01-08
        相关资源
        最近更新 更多