aniu01
aniu01

Reputation: 11

How do I change the values of my dictionary from list type to string type

I need to go from this output

3 ['and', 'may']
5 ['short']
6 ['coffee', 'monday', 'strong']

to this output

3 and may
5 short
6 coffee monday strong

this is my code so far:

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)

how can I convert the values of my dictionary, which are in list type, to a string type?

Upvotes: 0

Views: 47

Answers (2)

kederrac
kederrac

Reputation: 17322

you can use the print buil-in function with generator expression:

d = {3: ['may', 'and'], 5: ['short'], 6: ['monday', 'coffee', 'strong']}

print(*(' '.join(str(e) for e in (k, *v)) for k, v in d.items()), sep='\n')

output:

3 may and
5 short
6 monday coffee strong

Upvotes: 0

Abhishek Kulkarni
Abhishek Kulkarni

Reputation: 1767

You can try this following:

    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)

OR if you want to avoid using map try this :

    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)

Upvotes: 1

Related Questions