在不知道密钥的情况下访问python dict()的值

cba*_*wat 2 python dictionary

我有一本字典列表的字典.如下所示:

x = {'a':[{'p':1, 'q':2}, {'p':4, 'q':5}], 'b':[{'p':6, 'q':1}, {'p':10, 'q':12}]}

列表(值)的长度对于dict x的所有键都是相同的.我想得到任何一个值的长度,即列表而不必通过明显的方法 - >获取密钥,使用len(x [keys [0]])来获取长度.

我现在的代码:

val = None
for key in x.keys():
    val = x[key]
    break
    #break after the first iteration as the length of the lists is the same for any key
try:
    what_i_Want = len(val)
except TypeError:
    print 'val wasn't set'
Run Code Online (Sandbox Code Playgroud)

我对此并不满意,我相信可以做得更加"pythonic".

the*_*eye 5

这是最有效的方法,因为我们不创建任何中间列表.

print len(x[next(iter(x))])   # 2
Run Code Online (Sandbox Code Playgroud)

注意:要使此方法起作用,字典应至少包含一个键.