I have a dictionary in which the values are lists. I need to create a list of these lists in the dictionary
My dict (which is the input)
input = [
{
'key': 'list1',
'values': [4,5,2,3,4,5,2,3],
}
,{
'key': 'list2',
'values': [1,1,34,12,40,3,9,7],
}
]
The output I need:
[[4, 5, 2, 3, 4, 5, 2, 3], [1, 1, 34, 12, 40, 3, 9, 7]]
I’ve tried to write a code, but the output is wrong. The code I wrote:
lista_master = []
def compute_deviation(list_numbers):
for dic in list_numbers:
lista = list(dic.values())[1]
lista_master.append(lista)
print(lista_master)
The wrong output from my code:
[[4, 5, 2, 3, 4, 5, 2, 3]]
[[4, 5, 2, 3, 4, 5, 2, 3], [1, 1, 34, 12, 40, 3, 9, 7]]
What am I doing wrong and how can I fix it?
>Solution :
You are printing the value of lista_master every iteration of the loop, so a total 2 times in your case, you just need to move it outside the loop like so:
def compute_deviation(list_numbers):
lista_master = [] # I also moved the "lista_master" inside the function
for dic in list_numbers:
lista = list(dic.values())[1]
lista_master.append(lista)
print(lista_master) #<--- here is the change
now:
compute_deviation(input)
output:
[[4, 5, 2, 3, 4, 5, 2, 3], [1, 1, 34, 12, 40, 3, 9, 7]]