'How to return a string containing information about how many values exist for each key

I currently have the following:

 mydict = {'a': [1, 2, 3], 'b': [1, 2]}

I want to return a string containing quantities of items available in the dictionary. For example

a: 3
b: 2

However, I want my output to update if I add another key value pair to the dictionary. For example mydict['c'] = [1, 2, 3]

I have thought about how to do this and this is all that comes to mind:

def quantities() -> str:

     mydict = {'a': [1, 2, 3], 'b': [1, 2]}

     for k, v in mydict:
        print(f'{k}: {len(v)})

But I am not sure if this is correct. Are there any other ways to do this.



Solution 1:[1]

The statement:

for <variable> in mydict:

Iterates through only the keys of the dictionary. So, you can either use the key to get the item like:

mydict = {'a': [1, 2, 3], 'b': [1, 2]}
for k in mydict:
    print(f'{k}: {len(mydict[k])}')

Or use mydict.items() This makes it iterate through every (key, value). USe it as:

mydict = {'a': [1, 2, 3], 'b': [1, 2]}
for k, v in mydict.items():
    print(f'{k}: {len(v)}')

Solution 2:[2]

I don't think your sample code will work. I used this documentation and use sorted() I think what you want is something like this.

mydict = {'a': [1, 2, 3, 4], 'b': [1, 2]}

def quantities():
    for k, v in sorted(mydict.items()):
        print(k, len(v))
        
quantities()

Solution 3:[3]

You can do this with str.join and a generator expression:

def quantities(mydict):
    return '\n'.join('{}: {}'.format(k, len(v)) for k, v in mydict.items())

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Rory
Solution 3 luther