这是我的json:
{"data": [{"L": "Leinster"}, {"RN": "Roscommon"}, {"G": "Galway"}, {"LS": "Laois"}, {"LD": "Longford"}, {"OY": "Offaly"}, {"KK": "Kilkenny"}, {"SO": "Sligo"}, {"C": "Connaught"}, {"CO": "Cork"}, {"M": "Munster"}, {"WD": "Waterford"}, {"CE": "Clare"}]}
我想排序,以便dict将按照值的'abc'排序:
{"data": [ {"CE": "Clare"},{"C": "Connaught"}, {"CO": "Cork"}, {"G": "Galway"},{"KK": "Kilkenny"}, {"LS": "Laois"},{"L": "Leinster"}, {"LD": "Longford"}, {"M": "Munster"},{"OY": "Offaly"}, {"RN": "Roscommon"}, {"SO": "Sligo"}, {"WD": "Waterford"} ]}
一些想法?试过这个Python: sort this dictionary (dict in dict)
但这是排序值。不是字典中的值。
谢谢!
答案 0 :(得分:4)
对于Python 2
>>> d = {'data': [{'L': 'Leinster'}, {'RN': 'Roscommon'}, {'G': 'Galway'}, {'LS': 'Laois'}, {'LD': 'Longford'}, {'OY': 'Offaly'}, {'KK': 'Kilkenny'}, {'SO': 'Sligo'}, {'C': 'Connaught'}, {'CO': 'Cork'}, {'M': 'Munster'}, {'WD': 'Waterford'}, {'CE': 'Clare'}]}
>>> dict((k,sorted(v,key=dict.values)) for k,v in d.iteritems())
{'data': [{'CE': 'Clare'}, {'C': 'Connaught'}, {'CO': 'Cork'}, {'G': 'Galway'}, {'KK': 'Kilkenny'}, {'LS': 'Laois'}, {'L': 'Leinster'}, {'LD': 'Longford'}, {'M': 'Munster'}, {'OY': 'Offaly'}, {'RN': 'Roscommon'}, {'SO': 'Sligo'}, {'WD': 'Waterford'}]}
这是一个python 3解决方案,很高兴知道是否有比这更好的东西,因为我不喜欢它。
>>> {k:sorted(v,key=lambda x: tuple(x.values())) for k,v in d.items()}
{'data': [{'CE': 'Clare'}, {'C': 'Connaught'}, {'CO': 'Cork'}, {'G': 'Galway'}, {'KK': 'Kilkenny'}, {'LS': 'Laois'}, {'L': 'Leinster'}, {'LD': 'Longford'}, {'M': 'Munster'}, {'OY': 'Offaly'}, {'RN': 'Roscommon'}, {'SO': 'Sligo'}, {'WD': 'Waterford'}]}
答案 1 :(得分:1)
或者你可以简单地做
已更新以按值排序
In [41]: r={"data": [{"L": "Leinster"}, {"RN": "Roscommon"}, {"G": "Galway"}, {"LS": "Laois"}, {"LD": "Longford"}, {"OY": "Offaly"}, {"KK": "Kilkenny"}, {"SO": "Sligo"}, {"C": "Connaught"}, {"CO": "Cork"}, {"M": "Munster"}, {"WD": "Waterford"}, {"CE": "Clare"}]}
In [42]: for v in r.itervalues():
....: v.sort(key=dict.values)
....:
In [43]: r
Out[43]:
{'data': [{'CE': 'Clare'},
{'C': 'Connaught'},
{'CO': 'Cork'},
{'G': 'Galway'},
{'KK': 'Kilkenny'},
{'LS': 'Laois'},
{'L': 'Leinster'},
{'LD': 'Longford'},
{'M': 'Munster'},
{'OY': 'Offaly'},
{'RN': 'Roscommon'},
{'SO': 'Sligo'},
{'WD': 'Waterford'}]}
答案 2 :(得分:1)
又一种解决方案,因为越多越好!
>>> r={"data": [{"L": "Leinster"}, {"RN": "Roscommon"}, {"G": "Galway"}, {"LS": "Laois"}, {"LD": "Longford"}, {"OY": "Offaly"}, {"KK": "Kilkenny"}, {"SO": "Sligo"}, {"C": "Connaught"}, {"CO": "Cork"}, {"M": "Munster"}, {"WD": "Waterford"}, {"CE": "Clare"}]}
>>>
>>> map(functools.partial(list.sort, key=dict.values), r.itervalues())
[None]
>>>
>>> r
{'data': [{'CE': 'Clare'}, {'C': 'Connaught'}, {'CO': 'Cork'}, {'G': 'Galway'}, {'KK': 'Kilkenny'}, {'LS': 'Laois'}, {'L': 'Leinster'}, {'LD': 'Longford'}, {'M': 'Munster'}, {'OY': 'Offaly'}, {'RN': 'Roscommon'}, {'SO': 'Sligo'}, {'WD': 'Waterford'}]}