The problem is that every time a conditional is met and you make newDict[clave] = listP[i][0]
you assign a new string as the value of the key.
You would have to concatenate the new name to the string that already exists as a key associated with the range, if the key already exists in the dictionary, or create a new key-value pair if it does not previously exist, something like this:
listP = [['john', 20], ['alberto', 20], ['natalia', 30]]
new_dict = {}
for nombre, edad in listP:
if 18 <= edad <= 24:
if '18-24' in new_dict:
new_dict['18-24'] += (', ' + nombre)
else:
new_dict['18-24'] = nombre
elif 25 <= edad <= 35:
if '25-35' in new_dict:
new_dict['25-35'] += (', ' + nombre)
else:
new_dict['25-35'] = nombre
Concatenating strings is a very inefficient task given that they are immutable and each time you concatenate you create a new object. Instead you could use a list and then apply str.join
to create the strings if you wish:
listP = [['john', 20], ['alberto', 20], ['natalia', 30]]
new_dict = {}
for nombre, edad in listP:
if 18 <= edad <= 24:
if '18-24' in new_dict:
new_dict['18-24'].append(nombre)
else:
new_dict['18-24'] = [nombre]
elif 25 <= edad <= 35:
if '25-35' in new_dict:
new_dict['25-35'].append(nombre)
else:
new_dict['25-35'] = [nombre]
Or you can use collections.defaultdict
that avoids the explicit verification of the existence of the key:
from collections import defaultdict
listP = [['john', 20], ['alberto', 20], ['natalia', 30]]
new_dict = defaultdict(list)
for nombre, edad in listP:
if 18 <= edad <= 24:
new_dict['18-24'].append(nombre)
elif 25 <= edad <= 35:
new_dict['25-35'].append(nombre)
Later you can go through the dictionary and create the strings if you do not want lists as values:
for key in new_dict:
new_dict[key] = ", ".join(new_dict[key])
With what you get:
>>> new_dict
{'18-24': 'john, alberto', '25-35': 'natalia'}
for indice in range(len(lista))
is a very inefficient and little "pythonic" way to go through a list. Unless you intend to alter the iterable content while iterating, it is always better to use for-in
for such tasks.