我有一个像这样的字典:
dict1 = {'lion': ['gazelle'],'jackal': ['grass','zebra','gazelle'],'gazelle': ['grass','acacia leaves'],'zebra': ['grass']}
我在这里有此代码:
for x,y in sorted(dict1.items()):
print(x,":",sep="",end=" ")
print(','.join(y))
gazelle: grass,acacia leaves
jackal: grass,zebra,gazelle
lion: gazelle
zebra: grass
如您所见,键是排序的,而不是值.我也想按字母顺序对值进行排序,但是我不确定如何实现?
我想要的是:
gazelle: acacia leaves,grass
jackal: gazelle,grass,zebra
lion: gazelle
zebra: grass
很感谢任何形式的帮助!
最佳答案
您可以调用y中的值进行排序:
原文链接:https://www.f2er.com/python/533287.htmlfor x,'.join(sorted(y)))