【问题标题】:How to create a frequency dictionary with list of values in python 3.6如何在 python 3.6 中创建带有值列表的频率字典
【发布时间】:2020-03-16 21:15:08
【问题描述】:

我正在尝试在 python 3.6 中编写一个函数,它返回一个以项目计数为键的字典和一个具有该计数的项目列表。

下面是一个测试用例应该是什么样子的示例: 输入:{'x':3, 'y':3, 'z':100} 输出:{3: ['x', 'y'], 100: ['z']}

这是我目前所拥有的代码:

def get_count_items(key_count):
    # create blank dictionary
    count_items = {}
    #for each item_key in key_count:
    for item_key in key_count
    # retrieve its value (which is a count)
    # if the count (as key) exists in count_items:
    if item in count_items:
        count_items[item] += 1
    # append the item_key to the list
    # else:
    #add the count:[item_key] pair to count_items dictionary
    else:
        count_items[item] = 1

    for key, value in count_items.items():
    #return count_items dictionary
        return count_items

我的问题是如何将每个计数值设置为键,以及如何为具有该计数的每个项目制作相应的列表?

感谢您的帮助!

【问题讨论】:

    标签: python list dictionary python-3.6


    【解决方案1】:

    试试这个:

    d = {'x':3, 'y':3, 'z':100} 
    x={}
    for key, value in sorted(d.items()): 
        x.setdefault(value, []).append(key) 
    
    x
    {3: ['x', 'y'], 100: ['z']}
    
    

    【讨论】:

      【解决方案2】:

      为了采用不同的方法..你可以很容易地在 pandas 中做到这一点:

      import pandas as pd
      df = pd.DataFrame([in_dict]).T
      df['vars'] = df.index
      out_dict = df.groupby(0)['vars'].agg(list).to_dict()
      

      输出:

      {3: ['x', 'y'], 100: ['z']}
      

      可能有一种方法可以使用单独的行来初始化 df['vars'],或者可能根本不需要但无法让它工作

      编辑 - 可能不那么漂亮,但更短:

      df = pd.DataFrame({'vals':[*in_dict.values()],'vars':[*in_dict.keys()]})
      out_dict = df.groupby('vals')['vars'].agg(list).to_dict()
      

      【讨论】:

        【解决方案3】:

        试试这个:

        a = {'x':3, 'y':3, 'z':100}
        d = {}
        for x in a:
            if a[x] in d:
                d[a[x]].append(x)
            else:
                d[a[x]]=[x]
        print(d)
        

        【讨论】:

          【解决方案4】:
          from collections import defaultdict
          
          d = {'x':3, 'y':3, 'z':100} 
          
          # create defaultdict with list type. 
          res = defaultdict(list)
          
          # iterate over key value pair
          for k, v in d.items():
              res[v].append(k)
          print(res)
          # or
          print(dict(res))
          

          输出:

          defaultdict(<class 'list'>, {3: ['x', 'y'], 100: ['z']})
          {3: ['x', 'y'], 100: ['z']}
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2014-12-18
            • 1970-01-01
            • 2022-11-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多