Home > other >  values are not shown up when using the second for loop - Python
values are not shown up when using the second for loop - Python

Time:10-21

I'm was trying to do random selection in the data, but I was stuck when using for-loop to nest all data into an array.

Data

data = [
    {"Animal1": "Dog", "Animal2": "Cat", "Animal3": "Snake"},
    {"Animal1": "Mouse", "Animal2": "Ant", "Animal3": "Chicken"},
    {"Animal1": "Fish", "Animal2": "Elephant", "Animal3": "Fox"},
    {"Animal1": "rabbit", "Animal2": "sheep", "Animal3": "wolf"}
]

My code:

new_data = []

for rows in data:
    for row in rows:
        new_data.append(row)

print(new_data)

Output

['Animal1', 'Animal2', 'Animal3', 'Animal1', 'Animal2', 'Animal3', 'Animal1', 'Animal2', 'Animal3', 'Animal1', 'Animal2', 'Animal3']

Expected output

{
    "Animal1": "Dog", "Animal2": "Cat", "Animal3": "Snake",
    "Animal1": "Mouse", "Animal2": "Ant", "Animal3": "Chicken",
    "Animal1": "Fish", "Animal2": "Elephant", "Animal3": "Fox",
    "Animal1": "rabbit", "Animal2": "sheep", "Animal3": "wolf"
}

CodePudding user response:

I think you're looking for something like:

from collections import defaultdict

results = defaultdict(list)

for rows in data:
    for key, value in rows.items():
        results[key].append(value)

  • Related