【问题标题】:Build a dictionary containing for each keys, a set of associate values from a list of tuples为每个键构建一个字典,包含一组来自元组列表的关联值
【发布时间】:2021-02-08 12:37:13
【问题描述】:

我有一个这样的元组列表:

list = [(1,2),(1,3),(1,5),(0,8),(0,9),(0,1),(3,6),(3,7)]

我想用这样的关联值集构建一个字典:

result = {1:{2,3,5},0:{8,9,1},3:{6,7}}

我有这个代码:

return {x:y for (x,y) in list}

result = {1: 5, 0: 1, 3: 7}

但我只有最后一个值,我想要一个集合中的所有关联值。

提前致谢

【问题讨论】:

    标签: python list dictionary set tuples


    【解决方案1】:

    defaultdict 可以在不检查存在的情况下为键添加值

    from collections import defaultdict
    mylist = [(1,2),(1,3),(1,5),(0,8),(0,9),(0,1),(3,6),(3,7)]
    result = defaultdict(list)
    for item in mylist:
        result[item[0]].append(item[1])
    

    【讨论】:

      【解决方案2】:

      解决方案:
      这段代码 sn-p 应该可以解决您的问题陈述:

      lst = [(1,2),(1,3),(1,5),(0,8),(0,9),(0,1),(3,6),(3,7)]
      
      output_dict = dict()
      [output_dict[t[0]].add(t[1]) if t[0] in list(output_dict.keys()) else output_dict.update({t[0]: {t[1]}}) for t in lst]
      print(output_dict)
      

      输出:

      {1: {2, 3, 5}, 0: {8, 9, 1}, 3: {6, 7}}
      

      【讨论】:

        【解决方案3】:

        这应该对你有帮助:

        lst = [(1,2),(1,3),(1,5),(0,8),(0,9),(0,1),(3,6),(3,7)]
        result= {}
        
        [result.setdefault(x, set()).add(y) for x,y in lst]
        
        print(result)
        

        输出:

        {1: {2, 3, 5}, 0: {8, 9, 1}, 3: {6, 7}}
        

        【讨论】:

          【解决方案4】:

          如果你想要一个班轮:

          In [10]: original_list = [(1,2),(1,3),(1,5),(0,8),(0,9),(0,1),(3,6),(3,7),(1,2)]
          
          In [11]: {x: {r for(q, r) in original_list if q == x} for (x, y) in original_list}
          Out[11]: {1: {2, 3, 5}, 0: {1, 8, 9}, 3: {6, 7}}
          

          【讨论】:

            【解决方案5】:

            这里是:

            result = {}
            
            for x, y in list:
                if x not in result:
                    result[x] = []
                result[x].append(y)
            
            print(result)
            

            【讨论】:

              猜你喜欢
              • 2019-10-05
              • 2019-03-17
              • 1970-01-01
              • 2019-01-18
              • 2019-05-04
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多