Python-访问字典中的列表

时间:2021-06-22 05:48:00

标签: python

所以,我试图解决这个问题,我必须返回所有约会过的人的字典。

例如这个输入:

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

应该输出:

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

但我不知道如何保存名称,然后将其插入字典。我试过两次遍历列表,但没有成功。

下面是我用来返回必要字典的函数。

def return_all_dates(people_who_went_on_dates):
    pass

2 个答案:

答案 0 :(得分:1)

你可以这样做:

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)

答案 1 :(得分:1)

这是我的方法:

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' , '克里斯'], '克里斯': ['迈克尔']}