Add values from a list to a python dictionary

1

I'm making a code which has a list list which contains a name and an integer (which is your age) and I want you to add to your 'category' from your age if we could call you from That way, this is my code:

listP = [['john', 20], ['alberto', 20], ['natalia', 30]]
newDict = {}

for i in range(len(listP)):
    temp = listP[i][1]
    if temp >= 18 and temp <= 24:
        newDict['18-24'] = listP[i][0]
    elif temp >= 25 and temp <= 35:
        newDict['25-35'] = listP[i][0]

As an exit I get:

{'18-24': 'alberto', '25-35': 'natalia'}

And you should get output:

{'18-24': 'alberto, jonh', '25-35': 'natalia'}

Thank you in advance.

    
asked by Luis Miguel 31.03.2018 в 04:28
source

1 answer

2

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.

    
answered by 31.03.2018 / 04:46
source