Skip to content
Advertisement

Length key in dictonary

How can I find out the length of the values of the key? I have code:

keys = { 
    'id':[],
    'name': [ ],
    'adress': [],
}

keys['id'].append([1, 2, 3])
keys['name'].append(['nm1', 'nm2', 'test3'])
keys['adress'].append(['adr1', 'adr2'])

for key in keys:
    print(f'{key} : {key.__len__}')

It gives me: key : … (not length and count) And should:

id : 3
name : 3
adress: 2

How should I do it?

Advertisement

Answer

There are three problems with your code:

  1. __len__ is a method, not an attribute. You get the length of an iterable using the len function:
for key in keys:
    print(f'{key} : {len(key)}')

Docs for the built-in len function here

  1. with the code above you get the length of the keys, not the values.

With the loop for key in keys you get id, name and adress in the key variable. To get the actual values you have various ways, the most common is to use the .items() method:

for key, value in keys.items():
    print(f'{key} : {len(value)}')
  1. the way you populate the values will insert 1 item (a list) in each

the append method will add the argument you pass in to the list, in your case the whole lists, so the values will be lists containing 1 list each. If you want to have the values to contain 1,2,3 ,'nm1', 'nm2', 'test3' and 'adr1', 'adr2', you should use the extend method (docs on list methods):

keys['id'].extend([1, 2, 3])
keys['name'].extend(['nm1', 'nm2', 'test3'])
keys['adress'].extend(['adr1', 'adr2'])

To get the desired result, this will be your final code:

keys = { 
    'id':[],
    'name': [],
    'adress': [],
}

keys['id'].extend([1, 2, 3])
keys['name'].extend(['nm1', 'nm2', 'test3'])
keys['adress'].extend(['adr1', 'adr2'])

for key, value in keys.items():
    print(f'{key} : {len(value)}')
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement