gpt4 book ai didi

python - 根据子字典的值对字典中的子字典进行排序

转载 作者:太空宇宙 更新时间:2023-11-03 13:50:09 25 4
gpt4 key购买 nike

这是我的 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) 但这是排序值。不是字典中的值。

谢谢!

最佳答案

对于 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'}]}

关于python - 根据子字典的值对字典中的子字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10732383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com