【问题标题】:How I can convert a Python Tuple into Dictionary如何将 Python 元组转换为字典
【发布时间】:2019-08-24 06:12:51
【问题描述】:

为了将t = [('a', 1), ('b', 2), ('c', 3), ('a', 4)] 转换为dict,我希望输出为{'a':5,'b':2,'c':3} 而不是{'a':4,'b':2,'c':3}。 有没有办法把同一个键项的值加起来?

我正在使用这一行来转换元组:

dict((x,y) for x, y in t)

【问题讨论】:

  • 您是在问是否存在一个表达式?因为您肯定可以看到,从一个空字典开始编写一个 for 循环来检查每个元组,然后添加一个新的字典项或将一个值累积到现有的字典项中,这很容易编写。您在寻找更简单的东西吗?
  • 没错。我实际上是想用一行代码来表达它。

标签: python dictionary tuples


【解决方案1】:

我的方法:使用默认值 0 的 get

t = [('a', 1), ('b', 2), ('c', 3), ('a', 4)]
d = dict()
for x,y in t:
    d[x] = d.get(x, 0) + y;
print(d)

【讨论】:

    【解决方案2】:

    使用itertools.groupby:

    from itertools import groupby
    
    t = [('a', 1), ('b', 2), ('c', 3), ('a', 4)]
    
    f = lambda x: x[0]
    print({k: sum(x[1] for x in g) for k, g in groupby(sorted(t, key=f), key=f)})
    
    # {'a': 5, 'b': 2, 'c': 3}
    

    collections.defaultdict:

    from collections import defaultdict
    
    t = [('a', 1), ('b', 2), ('c', 3), ('a', 4)]
    
    d = defaultdict(int)
    for x in t:
        d[x[0]] += x[1]
    
    print(d)
    
    # {'a': 5, 'b': 2, 'c': 3}
    

    【讨论】:

    • OP 旁注:defaultdict 效率更高,因为 groupby 需要先排序。
    • 您的第一种方法是所有方法中最慢的。您可能想查看我的答案以了解详细信息
    【解决方案3】:
    from collections import Counter
    
    t = [('a', 1), ('b', 2), ('c', 3), ('a', 4)]
    
    h = Counter()
    for k, v in t:
        h[k] += v
    
    h
    Counter({'a': 5, 'c': 3, 'b': 2})
    

    【讨论】:

      【解决方案4】:

      您可以编写一个函数来检查该键是否已存在于字典中。这样的事情会起作用:

      d = dict()
      for x, y in t:
          if x in d:
              d[x]+=y
          else:
              d[x] = y
      

      这会给你正确的输出:

      {'a': 5, 'b': 2, 'c': 3}
      

      【讨论】:

        【解决方案5】:

        这几乎是来自collections.defaultdict 的示例

        from collections import defaultdict
        
        t = [('a', 1), ('b', 2), ('c', 3), ('a', 4)]
        char_to_int = defaultdict(int)
        
        for k, v in t:
            char_to_int[k] += v
        

        在解释器中验证

        In [1]: from collections import defaultdict
           ...:
           ...: t = [('a', 1), ('b', 2), ('c', 3), ('a', 4)]
           ...: char_to_int = defaultdict(int)
           ...:
           ...: for k, v in t:
           ...:     char_to_int[k] += v
           ...:
        
        In [2]: char_to_int
        Out[2]: defaultdict(int, {'a': 5, 'b': 2, 'c': 3})
        

        【讨论】:

          【解决方案6】:

          方法#1:

          这是最快的方法:

          t = [('a', 1), ('b', 2), ('c', 3), ('a', 4)]
          
          out = {}
          for x, y in t:
              if x in out:out[x] += y
              else:out[x] = y
          

          输出:

          {'a': 5, 'b': 2, 'c': 3}
          

          方法#2:

          这是最简单的方法:

          t = [('a', 1), ('b', 2), ('c', 3), ('a', 4)]
          
          d = dict.fromkeys(dict(t), 0)
          for x, y in t: d[x] += y
          

          输出:

          {'a': 5, 'b': 2, 'c': 3}
          

          我最快方法的证明:

          我使用timeit 来计算用户回答的每种方法需要多少时间。最快的是我的(方法#1):

          from timeit import timeit
          
          from itertools import groupby #for method 1
          from collections import defaultdict #for method 2 and 5
          from collections import Counter  #for method 3
          
          t = [('a', 1), ('b', 2), ('c', 3), ('a', 4)]
          
          
          
          ###############################
          #########  METHODS  ###########
          ###############################
          
          
          def method1():     #By Austin
              f = lambda x: x[0]
              {k: sum(x[1] for x in g) for k, g in groupby(sorted(t, key=f), key=f)}
          
          ###############################
          
          
          def method2():     #By Austin
              d = defaultdict(int)
              for x in t:
                  d[x[0]] += x[1]
          
          ###############################
          
          
          def method3():     #By Jean-Claude Arbaut
              h = Counter()
              for k, v in t:
                  h[k] += v
          
          ###############################
          
          
          def method4():     #By PHP
              d = dict()
              for x,y in t:
                  d[x] = d.get(x, 0) + y;
          
          ###############################
          
          
          def method5():     #By Skam
              char_to_int = defaultdict(int)
          
              for k, v in t:
                  char_to_int[k] += v
          
          ###############################
          
          
          def method6():     #By Aquiles Carattino
              d = dict()
              for x, y in t:
                  if x in d:
                      d[x]+=y
                  else:
                      d[x] = y
          
          ###############################
          
          
          def method7():   #My method 2
              d = dict.fromkeys(dict(t), 0)
              for x, y in t: d[x] += y
          
          ###############################
          
          
          def method8():   #My method 1
              out = {}
              for x, y in t:
                  if x in out:out[x] += y
                  else:out[x] = y
          
          
          
          print(timeit(method1))
          print(timeit(method2))
          print(timeit(method3))
          print(timeit(method4))
          print(timeit(method5))
          print(timeit(method6))
          print(timeit(method7))
          print(timeit(method8))
          

          我平台上的输出是:

          5.7539954  
          1.7488919999999997  
          4.2322991000000005
          1.0104673999999996
          1.3571206
          0.8095216999999995
          1.5506056999999984
          0.6387891000000003
          

          所以最快的方法是我回答的方法 8(方法 #1)。

          【讨论】:

            【解决方案7】:

            试试:

            >>> t = ((1, 'a'),(2, 'b'))
            >>> dict((y, x) for x, y in t)
            {'a': 1, 'b': 2}

            【讨论】:

            • 这不是 OP 想要的
            猜你喜欢
            • 1970-01-01
            • 2020-09-21
            • 2021-06-14
            • 1970-01-01
            • 2020-10-03
            • 1970-01-01
            • 2016-08-26
            • 2021-05-24
            相关资源
            最近更新 更多