繁体   English   中英

在python中将dict转换为排序的dict

[英]convert a dict to sorted dict in python

我想在python中将字典转换为排序的字典

data = pandas.read_csv('D:\myfile.csv')
for colname, dtype in data.dtypes.to_dict().iteritems():
    if dtype == 'object':
        print colname
        count = data[colname].value_counts()
        d = dict((str(k), int(v)) for k, v in count.iteritems())
        f = dict(sorted(d.iteritems(), key=lambda item: item[1], reverse = True)[:5])
        print f

        m ={}
        m["count"]= int(sum(count))    
        m["Top 5"]= f    
        print m    
        k = json.dumps(m)
        print k    
f = {'Gears of war 3': 6, 'Batman': 5, 'gears of war 3': 4, 'Rocksmith': 5, 'Madden': 3}

我想要的输出是:

f = {'Gears of war 3': 6, 'Batman': 5, 'Rocksmith': 5, 'gears of war 3': 4, 'Madden': 3}
k = {'count':24, 'top 5':{'Gears of war 3': 6, 'Batman': 5, 'Rocksmith': 5, 'gears of war 3': 4, 'Madden': 3}}

(按值的降序排列,结果应该是一个字典)

您无法对dict进行排序,因为字典没有排序。

相反,使用collections.OrderedDict

>>> from collections import OrderedDict
>>> d = {'Gears of war 3': 6, 'Batman': 5, 'gears of war 3': 4, 'Rocksmith': 5, 'Madden': 3}

>>> od = OrderedDict(sorted(d.items(), key=lambda x:x[1], reverse=True))
>>> od
OrderedDict([('Gears of war 3', 6), ('Batman', 5), ('gears of war 3', 4), ('Rocksmith', 5), ('Madden', 3)])

>>> od.keys()
['Gears of war 3', 'Batman', 'gears of war 3', 'Rocksmith', 'Madden']
>>> od.values()
[6, 5, 4, 5, 3]
>>> od['Batman']
5

您在 JSON 对象中看到的“顺序”没有意义,因为 JSON 对象是无序的 [ RFC4267 ]。

如果您想在 JSON 中进行有意义的排序,则需要使用列表(按照您想要的方式排序)。 像这样的东西是你想要的:

{
  "count": 24,
  "top 5": [
    {"Gears of war 3": 6},
    {"Batman": 5},
    {"Rocksmith": 5},
    {"gears of war 3": 4},
    {"Madden": 3}
  ]
}

给定相同的 dict d ,您可以通过以下方式生成排序列表(这是您想要的):

>>> l = sorted(d.items(), key=lambda x:x[1], reverse=True)
>>> l
[('Gears of war 3', 6), ('Batman', 5), ('Rocksmith', 5), ('gears of war 3', 4), ('Madden', 3)]

现在你只需将l传递给m['top5']并转储它:

m["Top 5"]= l
k = json.dumps(m)

有一个 apache 许可证库sortedcontainers具有SortedDict

 sudo pip install sortedcontainers 
from sortedcontainers import SortedDict
sorted_dict = SortedDict({'a': 1, 'b': 2, 'c': 3})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM