我有一个像这样的字典:
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
非常感谢您的帮助!
答案 0 :(得分:2)
您可以使用sorted
中的值调用y
:
for x,y in sorted(dict1.items()):
print(x,":",sep="",end=" ")
print(', '.join(sorted(y)))