Ответ 1
Вы близко.
idnum = 11
# The loop and 'if' are good
# You just had the 'break' in the wrong place
for id, idnumber in A.iteritems():
if idnum in idnumber.keys(): # you can skip '.keys()', it the default
calculate = some_function_of(idnumber[idnum])
break # if we find it we're done looking - leave the loop
# otherwise we continue to the next dictionary
else:
# this is the for loop 'else' clause
# if we don't find it at all, we end up here
# because we never broke out of the loop
calculate = your_default_value
# or whatever you want to do if you don't find it
Если вам нужно знать, сколько 11
есть в качестве внутренних клавиш dict
s, вы можете:
idnum = 11
print sum(idnum in idnumber for idnumber in A.itervalues())
Это работает, потому что ключ может быть только в каждом dict
один раз, поэтому вам просто нужно проверить, выходит ли ключ. in
возвращает True
или False
, которые равны 1
и 0
, поэтому sum
- это количество вхождений idnum
.