3

这是我的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"}]}

我想排序,以便字典将按值的“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:排序这个字典(字典中的字典) ,但这是对值进行排序。不是字典中的值。

谢谢!

4

3 回答 3

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'}]}
于 2012-05-24T06:46:04.940 回答
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'}]}
于 2012-05-24T07:02:55.523 回答
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'}]}
于 2012-05-24T06:52:59.883 回答