2

I would like to print the descriptions of the friends whose last names are "Geller" from a nested dictionary:

friends={
    "Rachel":{
        "job":"fashion",
        "last name":"Green",
        "description":" brave for starting life over",
    },
    "Monica":{
        "job":"culinary",
        "last name":"Geller",
        "description":"likes things clean",
    },
    "Phoebe":{
        "job":"musician/masseuse",
        "last name":"Buffay",
        "description":"somewhat of a question mark",
    },
     "Chandler":{
        "job":"statistical analysis and data reconfiguration",
        "last name":"Bing",
        "description":"the funny one",
    },
     "Joey":{
        "job":"actor",
        "last name":"Tribbiani",
        "description":"italian american actor, born in queens, 7 sisters, only boy, NY Knicks rule",
    },
     "Ross":{
        "job":"dinosaurs",
        "last name":"Geller",
        "description":"3 divorces",
    },
}

so far i tried saving the results from the below loop into a variable but only managed to print the names

for i in friends:
    print(friends[i]["description"])

the loop prints all of the descriptions but i only need to print one description

5
  • You don't need a loop at all. print(friends[name]["description"]) Commented May 17, 2024 at 22:35
  • You only need save the friend name in a varible, for example: friend_name = "Rachel" Later, you can access to the description of Rachel in the dict, with this line: description = friends[friend_name]["description"] Commented May 17, 2024 at 22:39
  • ok perhaps i should have worded it differently. what if i wanted to print the description of everyone whose last name is "Geller"? Im going to edit my original post Commented May 17, 2024 at 22:44
  • @Doll In this case, a way can be looped for all the elements of friends. for name, info in friends.items(): Later you need to certificate if the last name is “Geller” with if info.get("last name") == "Geller": Now, you can print the description like print(f"{name}: {info.get('description')}") Commented May 17, 2024 at 22:51
  • With a generator expression: print(*(x['description'] for x in friends.values() if x['last name'] == 'Geller'), sep='\n') Commented May 17, 2024 at 23:08

1 Answer 1

1

You can use a conditional to check whether or not the last name for that person is "Geller" like this:

for i in friends:
    if friends[i]['last name'] == 'Geller':
        print(friends[i]['description'])

This will print out the 'description' of all the friends whose last names are 'Geller'.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.