相关疑难解决方法(0)

如何在一次通过中检查多个键是否在dict中?

我想做的事情如下:

foo = {'foo':1,'zip':2,'zam':3,'bar':4}

if ("foo","bar") in foo:
    #do stuff
Run Code Online (Sandbox Code Playgroud)

如何检查'foo'和'bar'是否都在dict foo中?

python dictionary

190
推荐指数
9
解决办法
9万
查看次数

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

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

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 ×2

python ×2