📌  相关文章
📜  Python|在字典中按字母顺序对列表进行排序

📅  最后修改于: 2022-05-13 01:54:34.970000             🧑  作者: Mango

Python|在字典中按字母顺序对列表进行排序

在Python中,字典是一种非常有用的数据结构,通常用于将特定的键与value进行散列,以便有效地检索它们。

让我们看看如何在字典中按字母顺序对列表进行排序。

示例 #1:

# Python program to sort the list 
# alphabetically in a dictionary
dict ={
    "L1":[87, 34, 56, 12],
    "L2":[23, 00, 30, 10],
    "L3":[1, 6, 2, 9],
    "L4":[40, 34, 21, 67]
}
  
print("\nBefore Sorting: ")
for x in dict.items():
    print(x)
  
print("\nAfter Sorting: ")
  
for i, j in dict.items():
    sorted_dict ={i:sorted(j)}
    print(sorted_dict)
输出:
Before Sorting: 
('L2', [23, 0, 30, 10])
('L3', [1, 6, 2, 9])
('L4', [40, 34, 21, 67])
('L1', [87, 34, 56, 12])

After Sorting: 
{'L2': [0, 10, 23, 30]}
{'L3': [1, 2, 6, 9]}
{'L4': [21, 34, 40, 67]}
{'L1': [12, 34, 56, 87]}


示例 #2:

# Python program to sort the list 
# alphabetically in a dictionary
  
dict ={
    "L1":["Geeks", "for", "Geeks"],
    "L2":["A", "computer", "science"],
    "L3":["portal", "for", "geeks"],
}
  
print("\nBefore Sorting: ")
for x in dict.items():
    print(x)
  
print("\nAfter Sorting: ")
for i, j in dict.items():
    sorted_dict ={i:sorted(j)}
    print(sorted_dict)
输出:
Before Sorting: 
('L3', ['portal', 'for', 'geeks'])
('L1', ['Geeks', 'for', 'Geeks'])
('L2', ['A', 'computer', 'science'])

After Sorting: 
{'L3': ['for', 'geeks', 'portal']}
{'L1': ['Geeks', 'Geeks', 'for']}
{'L2': ['A', 'computer', 'science']}


示例#3:

# Python program to sort the list 
# alphabetically in a dictionary
dict={
    "L1":[87,34,56,12],
    "L2":[23,00,30,10],
    "L3":[1,6,2,9],
    "L4":[40,34,21,67]
}
  
print("\nBefore Sorting: ")
for x in dict.items():
    print(x)
  
sorted_dict = {i: sorted(j) for i, j in dict.items()}
print("\nAfter Sorting: ", sorted_dict)
输出:
Before Sorting: 
('L1', [87, 34, 56, 12])
('L2', [23, 0, 30, 10])
('L3', [1, 6, 2, 9])
('L4', [40, 34, 21, 67])

After Sorting:  {'L1': [12, 34, 56, 87], 
                 'L2': [0, 10, 23, 30],
                 'L3': [1, 2, 6, 9], 
                 'L4': [21, 34, 40, 67]}