【发布时间】:2016-05-27 10:50:59
【问题描述】:
我有一本 Python 2.7 字典。
我需要快速计算所有键的数量,包括每个字典中的键。
所以在这个例子中,我需要所有键的数量为 6:
dict_test = {'key2': {'key_in3': 'value', 'key_in4': 'value'}, 'key1': {'key_in2': 'value', 'key_in1': 'value'}}
我知道我可以使用 for 循环遍历每个键,但我正在寻找一种更快的方法来执行此操作,因为我将拥有数千/数百万个键并且这样做是无效的:
count_the_keys = 0
for key in dict_test.keys():
for key_inner in dict_test[key].keys():
count_the_keys += 1
# something like this would be more effective
# of course .keys().keys() doesn't work
print len(dict_test.keys()) * len(dict_test.keys().keys())
【问题讨论】:
-
虽然你不要求这个,但如果你想要 distinct 键的数量,那么你可以做类似
len(set(itertools.chain(dict_test, *dict_test.values())))
标签: python python-2.7 dictionary