删除具有零数组作为值的键的方法

时间:2018-12-04 08:31:57

标签: python numpy dictionary

我将dict嵌套如下:

 u'dvlRaw':{
   u'diagnosticInfoUDP': { 
      u'clientConnected': array([0, 0, 0, 0, 0, 0, 0,0, 0,0], dtype=uint8),
      u'channel': array([1, 1, 1, ..., 1, 1, 1], dtype=uint32)
     }
 }

如何删除键,值对,其值中包含整个零数组。 零数组的位置可能不是恒定的,有时可能是child_dictionary的值,有时可能是child_dictionary的child的值。 是否有一种通用的方法可以消除出现的零数组在任何child_dictionary中的位置

4 个答案:

答案 0 :(得分:1)

使用numpy.any检查每个数组是否包含任何非零值:

import numpy as np

diagnosticInfoUDP = dictionary['dvlRaw']['diagnosticInfoUDP']
for key in list(diagnosticInfoUDP):
    if not np.any(diagnosticInfoUDP[key]):
        del diagnosticInfoUDP[key]

编辑:从任意嵌套的字典中删除仅零数组的一般解决方案:

def clean_dict(dictionary):
    for key, value in list(dictionary.items()):
        if isinstance(value, np.ndarray) and not np.any(value):
            del dictionary[key]
        elif isinstance(value, dict):
            clean_dict(value)

答案 1 :(得分:1)

这是一种非常基本的方法:

d = {'dvlRaw':{'diagnosticInfoUDP': {'clientConnected': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'channel': [1, 1, 1, 1, 1, 1]}}}


def all_zeroes(arr):
  return 0 in set(arr) and len(set(arr)) == 1

remove = []
for k, v in d['dvlRaw']['diagnosticInfoUDP'].items():
  if all_zeroes(v): remove.append(k) 

for k in remove:
  del d['dvlRaw']['diagnosticInfoUDP'][k]

print(d)
#=> {'dvlRaw': {'diagnosticInfoUDP': {'channel': [1, 1, 1, 1, 1, 1]}}}

答案 2 :(得分:1)

对于您定义的精确结构,可以对np.ndarray.any使用字典理解:

import numpy as np

dct = {u'dvlRaw': {u'diagnosticInfoUDP': 
       {u'clientConnected': np.array([0, 0, 0, 0, 0, 0, 0,0, 0,0], dtype='uint8'),
        u'channel': np.array([1, 1, 1, 1, 1, 1, 1], dtype='uint32')}}}

res = {u'dvlRaw': {u'diagnosticInfoUDP':
       {k: v for k, v in dct[u'dvlRaw'][u'diagnosticInfoUDP'].items() if v.any()}}}

print(res)

{'dvlRaw': {'diagnosticInfoUDP': {'channel': array([1, 1, 1, 1, 1, 1, 1], dtype=uint32)}}}

答案 3 :(得分:0)

您可以从现有字典中创建一个新的嵌套字典:

bob = {"bob" : {"nob": np.zeros(10), "dob" : np.ones(10)}}

bob2 = {k : {k2 : bob[k][k2] for k2 in bob[k].keys() if not (bob[k][k2] == 0).all()} for k in bob.keys()}

在此示例中,我的嵌套字典名为bob,我通过以下方式从中构建了一个新的嵌套字典:

  • k中的每个键bob,建立一个新的字典。
  • 如果k2不全为零,则新字典将仅包含bob[k]中的bob[k][k2]键。

请注意,我正在遍历bob k的键,并从每个内部字典的键“ k2”开始迭代,我正在使用键来提取值。