2012-01-10 52 views
3

我有以下对象比较词典内容与对象

class LidarPropertiesField(object): 
    osversion = '' 
    lidarname = '' 
    lat = 0.0 
    longit = 0.0 
    alt = 0.0 
    pitch = 0.0 
    yaw = 0.0 
    roll = 0.0 
    home_el = 0.0 
    home_az = 0.0 
    gps = 0 
    vad = 0 
    ppi = 0 
    rhi = 0 
    flex_traj = 0 
    focuse = 0 
    type = 0 
    range_no = 0 
    hard_target = 0 
    dbid = 0 

我也有相同的字段字典,是可以比较与词典字段的对象字段在for循环?

+0

LIDAR =真棒 – 2012-10-22 08:37:31

回答

5

假设dict被称为d,这将检查LidarPropertiesFielddd所有密钥的相同值:

for k, v in d.iteritems(): 
    if getattr(LidarPropertiesField, k) != v: 
     # difference found; note, an exception will be raised 
     # if LidarPropertiesField has no attribute k 

或者,你可以在类转换为dict喜欢的东西

dict((k, v) for k, v in LidarPropertiesField.__dict__.iteritems() 
      if not k.startswith('_')) 

并与==比较。

注意跳过与_开头的所有类的属性,以避免__doc____dict____module____weakref__

+0

为了更好的结果,如果没有isCallable(V)可以加入。在运营商模块中找到。 – 2012-01-10 18:24:01

+0

@RomanSusi:我不明白。 – 2012-01-10 18:25:23

+0

你不一定想比较对象的方法......或者你可能会。 – Cyclone 2012-01-10 18:29:35

1

看看内置功能getattr()

class Foo: 
    bark = 0.0 
    woof = 1.0 

foo = Foo() 

foo_dict = dict(bark = 1.0, woof = 1.0) 
for k in foo_dict.keys(): 
    print 'Checking', k 
    print getattr(foo, k) 
    print foo_dict[k] 
    if foo_dict[k] == getattr(foo, k): 
     print ' matches' 
    else: 
     print ' no match' 

给出了结果:

Checking woof 
1.0 
1.0 
    matches 
Checking bark 
0.0 
1.0 
    no match 
+0

这种方式可以省略某些属性(如果它们不是foo_dict中的键)并且比较结果将无效。 – 2012-01-10 18:18:41