Hackxx
Hackxx

Reputation: 71

Python for loops inquiry

With a dictionary with keys being names and values being the association they're part of as one of the parameters, and a person I'm interested as another parameter, the goal is to get all the people he's in the groups with into a new list.

For example,

connections =  {
    'Alex Dunphy': ['Orchestra', 'Chess Club'], 
    'Manny Delgado': ['Chess Club'], 
    'Cameron Tucker': ['Clown School', 'Wizard of Oz Fan Club'], 
    'Claire Dunphy': ['Parent Teacher Association'], 
    'Gloria Pritchett': ['Parent Teacher Association'], 
    'Phil Dunphy': ['Real Estate Association'], 
    'Mitchell Pritchett': ['Law Association']
}

What I did was invert the order so that it was key -> association and values being people that are involved in that association and trying to append to an empty list from there, but for some reason it's not working. The code is the following.

if person_to_networks != {}:
    ppl = []
    network_to_people = {}

    for key in person_to_networks:
        for i in range(len(person_to_networks[key])):
            if person_to_networks[key][i] not in network_to_people:
                ppl.append(key)
                network_to_people[person_to_networks[key][i]] = [key]
            elif person_to_networks[key][i] in network_to_people:
                network_to_people[person_to_networks[key][i]].append(key)


for net in network_to_people:
    for i in range(len(network_to_people[net])):
        if person in network_to_people[net]:
            test.append(network_to_people[net][i])
print(test)

The output is:

[]

The desired output is:

['Manny Delgado', 'Alex Dunphy', 'Alex Dunphy']

if the person selected was Alex Dunphy

Any tips and stuff?

Upvotes: 1

Views: 67

Answers (4)

hongshuning
hongshuning

Reputation: 77

Another answer: remove duplicate persons in test.

my_nets = set(connections[person])
for candidate, candidate_nets in connections.items():
    if set(candidate_nets) & my_nets:
        test.append(candidate)

Upvotes: 0

hongshuning
hongshuning

Reputation: 77

Try this. The order of test is not the same as what you want.

for net in connections[person]:
    for candidate, candidate_nets in connections.items():
        if net in candidate_nets:
                test.append(candidate)

Upvotes: 0

Cyphase
Cyphase

Reputation: 12002

The get_associates() function does what you want.

from __future__ import print_function  # For Python 2/3 support

demo_affiliations = {
    'Alex Dunphy': ['Orchestra', 'Chess Club'],
    'Manny Delgado': ['Chess Club'],
    'Cameron Tucker': ['Clown School', 'Wizard of Oz Fan Club'],
    'Claire Dunphy': ['Parent Teacher Association'],
    'Gloria Pritchett': ['Parent Teacher Association'],
    'Phil Dunphy': ['Real Estate Association'],
    'Mitchell Pritchett': ['Law Association'],
    }
demo_person = 'Alex Dunphy'


# This is the main function; it'll take affiliations and a person
# as arguments, and returns a list of associates.


def get_associates(affiliations, person):
    associates = []
    persons_organizations = set(affiliations[person])

    for possible_associate, organizations in affiliations.items():
        intersection = set(organizations).intersection(persons_organizations)
        num_intersections = len(intersection)

        if intersection:  # This isn't needed, but it's more readable
            associates.extend([possible_associate] * num_intersections)

    return associates


def main(affiliations, person):
    associates = sorted(get_associates(affiliations, person))
    print('Associates:', associates)


if __name__ == '__main__':
    main(demo_affiliations, demo_person)

Upvotes: 1

Dleep
Dleep

Reputation: 1065

Instead of editing your code, i'd say this is a clearer solution:

for net in network_to_people:
    if person in network_to_people[net]:
        test.extend(network_to_people[net]) 
# extend does exactly what you'd think it does. 
# l = [2,3], with l.extend([4,4]) l becomes [2,3,4,4]

Upvotes: 0

Related Questions