【问题标题】:How do I pair up multiple keys with one values from a dictionary through a function?如何通过函数将多个键与字典中的一个值配对?
【发布时间】:2021-12-01 22:00:25
【问题描述】:

我有以下问题,我不知道该怎么办。有人可以帮忙吗???

“您正在举办派对,并希望将志趣相投的人配对。 您已经收集了有关您的每位客人最喜欢的兴趣的数据 像这样的字典:

兴趣 = { 'Sophia' : '电脑', 'Anders' : '跳舞', 'Mette' : “跳舞”、“光”:“计算机”、“Riko”:“划船”、“巨魔”: “划船”,“莎拉”:“划船”}

为了能够在聚会上快速推荐主题,您需要将其转换为 字典转换成不同的布局。

你的任务是编写一个函数 transform_dictionary 作为参数 一个字典,例如上面的字典,并返回一个字典,其中 每个键都是一个兴趣,值是所有共享这个的人的列表 兴趣。 例如,对于上面的列表,返回的字典是 (不考虑元素的特定顺序)

我需要打印:

{'计算机':['Sophia','Hikari'],'跳舞':['Anders','Mette'],'划船':['Riko','Troels','Sarah']}

这是我目前所拥有的:

    interests = {
        'Sophia' : 'Computer',
        'Anders' : 'Dancing',
        'Mette' : 'Dancing', 
        'Hikari' : 'Computer',
        'Riko' : 'Rowing', 
        'Troels' : 'Rowing',
        'Sarah' : 'Rowing'
    }
    
    # comvert dictionary into a different layout.
    
    def transform_dictionary(interests):
        new_dict = {}
        key_list = []
        
        for k, v in new_dict:
            if value in new_dict:
            new_dict[value] = k
        return {}
        
    
    print(transform_dictionary(interests)) 

【问题讨论】:

  • 你遍历空的new_dict,它什么都不做

标签: python function dictionary


【解决方案1】:

您可以使用collections.defaultdict(list),然后只使用append,如下所示:

from collections import defaultdict
dct = defaultdict(list)

for k,v in interests.items():
    dct[v].append(k)

输出:

{'Computer': ['Sophia', 'Hikari'],
 'Dancing': ['Anders', 'Mette'],
 'Rowing': ['Riko', 'Troels', 'Sarah']}

【讨论】:

    【解决方案2】:

    你可以这样做:

    interests = {
        'Sophia' : 'Computer',
        'Anders' : 'Dancing',
        'Mette' : 'Dancing', 
        'Hikari' : 'Computer',
        'Riko' : 'Rowing', 
        'Troels' : 'Rowing',
        'Sarah' : 'Rowing'
    }
    
    # convert dictionary into a different layout.
    
    def transform_dictionary(interests):
        new_dict = {}
        for v in interests.values():
            new_dict[v] = [i for i in interests if interests[i] == v]
        return new_dict
        
    
    print(transform_dictionary(interests))
    

    输出:

    {'Computer': ['Sophia', 'Hikari'], 'Dancing': ['Anders', 'Mette'], 'Rowing': ['Riko', 'Troels', 'Sarah']}
    

    【讨论】:

      【解决方案3】:

      这行得通:

      def transform_dictionary(interests):
          new_dict = {}
          for key, value in interests.items():
              if not value in new_dict:
                  new_dict[value] = [key]
              else:
                  new_dict[value] += [key]
          return new_dict
      

      【讨论】:

        猜你喜欢
        • 2021-10-29
        • 2021-05-12
        • 2021-08-04
        • 1970-01-01
        • 1970-01-01
        • 2018-04-13
        • 1970-01-01
        • 2014-12-31
        • 2021-04-29
        相关资源
        最近更新 更多