小编geo*_*ian的帖子

如何优雅地检查字典是否具有给定的结构?

我有一个具有以下结构的字典:

D = {
   'rows': 11,
   'cols': 13,
   (i, j): {
              'meta': 'random string',
              'walls': {
                  'E': True,
                  'O': False,
                  'N': True,
                  'S': True
              }
           }
}
# i ranging in {0 .. D['rows']-1}
# j ranging in {0 .. D['cols']-1}
Run Code Online (Sandbox Code Playgroud)

我被要求编写一个函数,它接受一个任意对象作为参数,并检查它是否具有该结构.这就是我写的:

def well_formed(L):
    if type(L) != dict:
        return False
    if 'rows' not in L:
        return False
    if 'cols' not in L:
        return False

    nr, nc = L['rows'], L['cols']

    # I should also check the int-ness of nr and …
Run Code Online (Sandbox Code Playgroud)

python dictionary

19
推荐指数
2
解决办法
3522
查看次数

标签 统计

dictionary ×1

python ×1