对于哈希来说,Perl的'if exists'的Python等价物是什么?

fly*_*zai 0 python python-2.7

我正在编写一个工作脚本,并且需要能够创建一个数组哈希,检查哈希(或字典)中是否存在密钥,如果确实存在,我会从新的汇总一些值换行到现有的哈希值.这是我在Perl中的代码,Python中的翻译是什么?

if (exists($rollUpHash{$hashKey}))
        {
          say("Same key found, summing up!")
          $rollUpHash{$hashKey}[14] += $lineFields[14];
          $rollUpHash{$hashKey}[15] += $lineFields[15];
          $rollUpHash{$hashKey}[16] += $lineFields[16];
          $rollUpHash{$hashKey}[17] += $lineFields[17];
          $rollUpHash{$hashKey}[24] += $lineFields[24];
          push @{$rollUpHash{$hashKey}}, $sumDeduct_NonDeduct_ytd;
          # print %rollUpHash;
        }
      else
        {
          $rollUpHash{$hashKey} = \@lineFields;
        }
Run Code Online (Sandbox Code Playgroud)

小智 6

如果您只是检查密钥是否存在,您可以这样做 if "key" in your_dictionary

编辑:

要处理问题的非预期的第二部分,关于将新值添加到数组,您可以执行类似的操作

# -1 will give you the last item in the list every time
for key, value in nums.iteritems():
    nums[key].append(value[-1]+value[-1])
Run Code Online (Sandbox Code Playgroud)