Home > front end >  How do I append values from a list of dictionaries into a new list?
How do I append values from a list of dictionaries into a new list?

Time:11-12

Below is a python program that can traverse through a list of dictionaries. But, the program return each values for a given day separately. I want the values to be appended into a list. kindly help!

temperatures = [
    {
        'monday': 12,
        'wednesday': 13,
        'friday': 14
    },
    {
        'monday': 10,
        'friday': 12
    },
    {
        'tuesday': 10,
        'thursday': 11,
        'saturday': 12
    },
]



def average(temperatures, day):
    for x in temperatures:
        n = []
        for i, j in x.items():
            if i == day:
                n.append(j)
                return(n)

print(average(temperatures, 'monday'))

CodePudding user response:

In python you would typically do this with a list comprehension:

temperatures = [
    {
        'monday': 12,
        'wednesday': 13,
        'friday': 14
    },
    {
        'monday': 10,
        'friday': 12
    },
    {
        'tuesday': 10,
        'thursday': 11,
        'saturday': 12
    },
]



def average(temperatures, day):
    return [week[day] for week in temperatures if day in week]

print(average(temperatures, 'monday'))
# [12, 10]

That basically says for each item in the list, if the day is in the item, look up the day and add it to the output. Note that dictionaries can be indexed directly by key: week[day]. There is no reason to loop over the items to look for a key.

CodePudding user response:

Without List Comprehension, we can use the typical for loop with one if to find if the day that is searched is defined or not.

temperatures = [
{
    'monday': 12,
    'wednesday': 13,
    'friday': 14
},
{
    'monday': 10,
    'friday': 12
},
{
    'tuesday': 10,
    'thursday': 11,
    'saturday': 12
},
]



def average(temp, day):
    days = []
    for obj in temp:
        parsed = dict(obj)
        if parsed.get(day) is not None:
           days.append(parsed.get(day))
        
    return days

print(average(temperatures, 'monday'))
# [12,10]

This solution is more beginner-friendly since list comprehension is an advanced topic in my point of view. Bu the better solution is from @Mark

CodePudding user response:

temperatures = [
    {
        'monday': 12,
        'wednesday': 13,
        'friday': 14
    },
    {
        'monday': 10,
        'friday': 12
    },
    {
        'tuesday': 10,
        'thursday': 11,
        'saturday': 12
    },
]



def average(temperatures, day):
    n = []  
    for x in temperatures:
        n = [] 
        for i, j in x.items():
            if i == day:
                n.append(j)
    return(n)          

print(average(temperatures, 'monday'))

This is the correct answer to your implementation. Basically the return statement should be made after you are done looping through the list.

  • Related