我有一条口述如下:

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

非常感谢您的帮助!

最佳答案

您可以使用sorted中的值调用y

for x,y in sorted(dict1.items()):
    print(x,":",sep="",end=" ")
    print(', '.join(sorted(y)))

09-12 08:33