如何将字典的值从列表类型更改为字符串类型

问题描述 投票:0回答:1

我需要从此输出中转到

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)

如何将列表类型的字典值转换为字符串类型?

python-3.x string list dictionary type-conversion
1个回答
1
投票

您可以尝试以下操作:

    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)
© www.soinside.com 2019 - 2024. All rights reserved.