代码之家  ›  专栏  ›  技术社区  ›  jsp

按最高频率键对字典排序

  •  2
  • jsp  · 技术社区  · 9 年前

    我正在整理一系列字典。并希望返回按键的频率(从大到小)排序的orderedDictionary。

     data = [{'123':'abc'}, {'123':'def'}, {'125':'123'}, {'125':'123243'}, {'125':'12312'} ]
    

    这就是我尝试过的,但这似乎不是解决这个问题的最具毒气的方式。有什么建议吗?

    freq_dict = {}
        for x_dict in data:
            for key in x_dict:
                if key in freq_dict:
                    freq_dict[key] = freq_dict[key] + 1
                else:
                    freq_dict[key] = 1
        s = [(k, freq_dict[k]) for k in sorted(freq_dict, key=freq_dict.get, reverse=True)] 
        print(s)
    
    2 回复  |  直到 9 年前
        1
  •  2
  •   Dewald Abrie    9 年前

    这个怎么样:

    from collections import Counter
    
    # input data
    data = [{'123': 'abc'}, {'123': 'def'}, {'125': '123'}, {'125': '123243'}, {'125': '12312'}]
    
    # count occurrence of first key in each dict in list
    # this produces a dictionary with the data's keys
    # ('123', '125', etc) as keys and the counts as values
    counts = Counter([list(d.keys())[0] for d in data])
    
    # sort by descending frequency of keys
    data_sorted = sorted(
        data,
        key=lambda item: counts[list(item.keys())[0]], # function to lookup freq from counts
        reverse=True # descending order
    )
    
    print(data_sorted)
    

    这导致:

    [{'125': '123'}, {'125': '123243'}, {'125': '12312'}, {'123': 'abc'}, {'123': 'def'}]
    

        2
  •  1
  •   Rick SilentGhost    9 年前

    获取字典键频率的最简单方法可能是 use a collections.Counter . 其工作原理如下:

    from collections import Counter
    
    freq = Counter(k for d in data for k in d)
    

    现在 freq 是一个字典,其中每个键都作为一个键,该键出现的次数就是该值。使用 sorted key

    freq_list = sorted(freq, key=freq.get)
    

    使用 .reverse() 要将列表切换到降序:

    freq_list.reverse()
    

    最后,使用 功能,带有可选 钥匙 index 您的方法 freq_list

    result = sorted(data, key = lambda d: freq_list.index(list(d)[0]))
    

    解释 参数 已排序 已排序 钥匙

    例如,当提供 get() 方法,结果将根据关联字典的自然顺序进行排序 get 返回给定键的值。当提供 index() 方法,则项目排序顺序将与该其他列表中的项目顺序匹配。