我需要从此输出中转到
3 ['and', 'may']
5 ['short']
6 ['coffee', 'monday', 'strong']
至此输出
3 and may
5 short
6 coffee monday strong
到目前为止,这是我的代码:
dictionary = {6:['monday', 'coffee', 'strong'], 5:['short'], 3:['may', 'and']}
def print_keys_values_inorder(dictionary):
for key in sorted(dictionary):
print(key , sorted(dictionary[key]))
print_keys_values_inorder(dictionary)
如何将列表类型的字典值转换为字符串类型?
您可以尝试以下操作:
dictionary = {6: ['monday', 'coffee', 'strong'], 5: ['short'], 3: ['may', 'and']}
def print_keys_values_inorder(dictionary):
for key in sorted(dictionary):
print(key, ' '.join(map(str, sorted(dictionary[key]))))
print_keys_values_inorder(dictionary)
或者,如果您想避免使用地图,请尝试此:
dictionary = {6: ['monday', 'coffee', 'strong'], 5: ['short'], 3: ['may', 'and']}
def print_keys_values_inorder(dictionary):
for key in sorted(dictionary):
print(key, *sorted(dictionary[key]))
print_keys_values_inorder(dictionary)