我想检查字典是否包含与键列表中完全相同的键(不多也不少)。我目前正在使用all()
和长度检查来做到这一点。有没有更好的办法?谢谢!
d = {'1': 'one', '3': 'three', '2': 'two'}
key_list = ['1', '2', '3']
all(col in d for col in key_list) and len(d) == 3
True
关于什么
set(d) == set(key_list)
@gmds指出,set(d)
等于set(d.keys())
列表非常适合维护订单,但set
更适合检查会员资格:
d = {'1': 'one', '3': 'three', '2': 'two'}
key_list = set(['1', '2', '3'])
all(col in d for col in key_list) and len(d) == 3
set
的查找时间为O(1),而list
为O(N)
你可以这样做:
>>> d = {'1': 'one', '3': 'three', '2': 'two'}
>>> key_list = ['1', '2', '3']
>>> sorted(d) == sorted(key_list)
True
>>>