1

So, I am trying to solve this problem where I have to return a dictionary of all people who went on dates.

For example, this input:

[
    ["john", "amy"],
    ["abby", "john"],
    ["john", "michael"],
    ["michael", "chris"],
]

Should output:

{
    "john": set(["amy", "abby", "michael"]),
    "amy": set(["john"]),
    "abby": set(["john"]),
    "michael": set(["john", "chris"]),
    "chris": set(["michael"]),
}

but I have no idea how I can save the names and then insert it into a dictionary. I've tried looping through the list twice, but no luck.

Below, is the function that I've been using to return the necessary dictionary.

def return_all_dates(people_who_went_on_dates):
    pass
1
  • 1
    Do you know how to create an empty dictionary? How to add an entry to a dictionary? How to add an item to a set? Commented Jun 22, 2021 at 5:52

2 Answers 2

1

you can do it like this:

dates = dict()

for row in people_who_went_on_dates:
    person1, person2 = row
    if person1 not in dates:
        dates[person1] = set()
    if person2 not in dates:
        dates[person2] = set()
    dates[person1].add(person2)
    dates[person2].add(person1)
Sign up to request clarification or add additional context in comments.

1 Comment

can be simplified using dates.setdefault(row[0], set()).add(row[1])
1

Here is my approach:

data = [
    ["john", "amy"],
    ["abby", "john"],
    ["john", "michael"],
    ["michael", "chris"],
]

def return_dates(all_dates):

    #Create empty dictionary
    dates = {}

    #Iterate over each date
    for date in all_dates:

        #Add first person if not exists in the dictionary
        if date[0] not in dates:

            #Assign value with a list of 1 element
            dates[date[0]] = [date[1]]

        #Add second person too if not exists too
        if date[1] not in dates:

            #Assign value with a list of 1 element
            dates[date[1]] = [date[0]]
        
        #if one or both persons exists in the dictionary, we do different steps
        #Add second person to the first person list only if it does not exists
        if date[1] not in dates[date[0]]:

            #List method append to add a new element
            dates[date[0]].append(date[1])

        #Add first person to the second person list only if it does not exists
        if date[0] not in dates[date[1]]:

            dates[date[1]].append(date[0])  
    
    #return dictionary
    return dates
            
result = return_dates(data)

print(result)

{'john': ['amy', 'abby', 'michael'], 'amy': ['john'], 'abby': ['john'], 'michael': ['john', 'chris'], 'chris': ['michael']}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.