Home > Net >  How can I print hello and all female members
How can I print hello and all female members

Time:10-17

test.json

{
    "A Company":[{"female":["Jessica","Eve"]},{"male":["Mike","Peter"]}],
    "B Company":[{"female":["Laura","Pamela"]},{"male":["Mark","Steve"]}]
}

test.py

import json

f = open('test.json',)
data = json.load(f)
for v in data.values():
    for element in v:
        print(element)

Output:

{'female': ['Jessica', 'Eve']}
{'male': ['Mike', 'Peter']}
{'female': ['Laura', 'Pamela']}
{'male': ['Mark', 'Steve']}

How can I print this: "Hello Jessica" "Hello Eve" "Hello Laura" "Hello Pamela"?

CodePudding user response:

You can use an iterator to extract then names and a for-loop to print the greetings without building an intermediate list:

data = {
    "A Company":[{"female":["Jessica","Eve"]},{"male":["Mike","Peter"]}],
    "B Company":[{"female":["Laura","Pamela"]},{"male":["Mark","Steve"]}]
}

names = (name for groups in data.values() 
              for group in groups 
              for name in group.get("female",[]))


for name in names: print("Hello",name)

Hello Jessica
Hello Eve
Hello Laura
Hello Pamela

CodePudding user response:

You missed the innermost loop, where you iterate the inner records and check if they are Males or Females.

Please see the example:

import json

json_file = """
{
    "A Company":[{"female":["Jessica","Eve"]},{"male":["Mike","Peter"]}],
    "B Company":[{"female":["Laura","Pamela"]},{"male":["Mark","Steve"]}]
}
"""

parsed = json.loads(json_file)

for val in parsed.values():
    for record in val:
        # This below is the innermost loop
        for key, value in record.items():
            # If it's female then we use list comprehension to print the greetings
            if key == "female":
                [print(f"Hello {name}") for name in value]

  • Related