-3

I want to print the key and its length.

So my desired result would be L1: 4, L2: 2, etc...

Here's the code I have so far. Any suggestions would be greatly appreciated

dic1 = {'L1': ['NY', 'CT', 'NH', 'MA'], 'L2': ['TX', 'NM'], 'L3': ['CA', 'WA', 'AZ'], 'L4': ['ND', 'SD','WY', 'ID'], 
'L5':['UT'],'L6':['MN','WI','KY']}

for i in dic1.keys():
Batata
  • 98
  • 1
  • 11
DevWms27
  • 17
  • 3
  • Try this - ```for k, v in dic1.items(): print(k, len(v))``` – Daniel Hao Sep 18 '22 at 01:02
  • I wrote your answer. But, consider reading [Iterating over dictionaries using 'for' loops](https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops). – Andre Nevares Sep 18 '22 at 01:19

3 Answers3

1

Try this:

for key in dic1.keys():
    print(key, len(dic1[key]))

Or this:

for key, value in dic1.items():
    print(key, len(value))
zalevskiaa
  • 174
  • 5
1

Would be this simple loop:


for k, v in dic1.items():
    print(k, len(v))

Output:

L1 4
L2 2
L3 3
L4 4
L5 1
L6 3

# or save into a list of tuples:
key_len = [(k, len(v)) for k, v in dic1.items()]
Daniel Hao
  • 4,922
  • 3
  • 10
  • 23
0
dic1 = {'L1': ['NY', 'CT', 'NH', 'MA'], 
        'L2': ['TX', 'NM'], 
        'L3': ['CA', 'WA', 'AZ'], 
        'L4': ['ND', 'SD','WY', 'ID'],
        'L5': ['UT'],
        'L6': ['MN','WI','KY']}

for key, value in dic1.items():
    print (key + ': ' + str(len(value)))

Output:

L1: 4
L2: 2
L3: 3
L4: 4
L5: 1
L6: 3

Check: Iterating over dictionaries using 'for' loops

Andre Nevares
  • 711
  • 6
  • 21