Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Lenght 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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)}')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading