【问题标题】:How to convert keys of dictionary into list of values of dictionary in python? [duplicate]如何将字典的键转换为python中字典的值列表? [复制]
【发布时间】:2020-10-24 05:43:46
【问题描述】:

如果值相同,我想将字典转换为字典列表。我在下面有一个示例数据:

my_dict={'Book 1':'Martha','Book 2':'Randy','Book 5':'Martha'}

现在我想把上面的字典转换成下面的输出:

my_dict={'Randy':['Book 2'],'Martha':['Book 1','Book 5']}

我如何在 python 中做到这一点?

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    这应该对你有帮助:

    my_dict={'Book 1':'Martha','Book 2':'Randy','Book 5':'Martha'}
    
    final_dict = {}
    
    for key in my_dict.keys():
        final_dict.setdefault(my_dict[key],[]).append(key)
        
    print(final_dict)
    

    输出:

    {'Martha': ['Book 1', 'Book 5'], 'Randy': ['Book 2']}
    

    【讨论】:

      【解决方案2】:

      使用collections.defaultdict 按值对键进行分组:

      from collections import defaultdict
      
      my_dict={'Book 1':'Martha','Book 2':'Randy','Book 5':'Martha'}
      
      d = defaultdict(list)
      for k, v in my_dict.items():
          d[v].append(k)
      
      print(d)
      

      输出:

      defaultdict(<class 'list'>, {'Martha': ['Book 1', 'Book 5'], 'Randy': ['Book 2']})
      

      【讨论】:

        【解决方案3】:

        您可以使用可用的defaultdict 函数。代码如下:

        from collections import defaultdict
        
        my_dict={'Book 1':'Martha','Book 2':'Randy','Book 5':'Martha'}
        new_dict = defaultdict(list)
        for i in my_dict:
            new_dict[my_dict[i]].append(i)
        
        new_dict = dict(new_dict)
        print(new_dict)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-11-11
          • 1970-01-01
          • 2016-01-10
          • 1970-01-01
          • 1970-01-01
          • 2015-07-17
          • 1970-01-01
          • 2012-07-12
          相关资源
          最近更新 更多