Python|从给定字典中按字母顺序对项目进行排序
给定一个字典,编写一个Python程序从给定字典中获取按字母顺序排序的项目并打印出来。让我们看看我们可以完成这项任务的一些方法。
代码 #1:使用 dict.items()
# Python program to sort the items alphabetically from given dictionary
# initialising _dictionary
dict = {'key1' : 'AGeek', 'key2' : 'For', 'key3': 'IsGeeks', 'key4': 'ZGeeks'}
# printing iniial_dictionary
print ("Original dictionary", str(dict))
# getting items in sorted order
print ("\nItems in sorted order")
for key, value in sorted(dict.items()):
print(value)
输出:
Original dictionary {‘key4’: ‘ZGeeks’, ‘key2’: ‘For’, ‘key1’: ‘AGeek’, ‘key3’: ‘IsGeeks’}
Items in sorted order
AGeek
For
IsGeeks
ZGeeks
代码 #2:使用 sorted()
# Python program to sort the items alphabetically from given dictionary
# initialising _dictionary
dict = {'key1' : 'AGeek', 'key2' : 'For', 'key3': 'IsGeeks', 'key4': 'ZGeeks'}
# printing iniial_dictionary
print ("Original dictionary", str(dict))
# getting items in sorted order
print ("\nItems in sorted order")
for key in sorted(dict):
print (dict[key])
输出:
Original dictionary {‘key4’: ‘ZGeeks’, ‘key2’: ‘For’, ‘key1’: ‘AGeek’, ‘key3’: ‘IsGeeks’}
Items in sorted order
AGeek
For
IsGeeks
ZGeeks