Home > database >  How do I print the length of each key in dictionary
How do I print the length of each key in dictionary

Time:09-18

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():

CodePudding user response:

Try this:

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

Or this:

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

CodePudding user response:

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()]

CodePudding user response:

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

  • Related