Length key in dictonary

Question:

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?

Asked By: Fa4stik

||

Answers:

You should use extend method not append if you want to add content of the list as a value. And try and read more about how the dictionary works.

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)}')
Answered By: Karol Milewczyk

try this:

    'id':[],
    'name':[],
    'adress': [],
}

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

for key in keys.keys():
    print(f'{key} : {len(keys[key][0])}')
Answered By: vagitus

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)}')
Answered By: Hrabal
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.