将字典内容与Object进行比较

时间:2012-01-10 17:57:14

标签: python object dictionary

我有以下对象

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循环中的字典字段进行比较?

2 个答案:

答案 0 :(得分:5)

假设dict被称为d,这将检查LidarPropertiesFieldd的所有键的d值是否与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__和{{1}}。

答案 1 :(得分: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