如何检查字典是否在列表中具有完全相同的键

问题描述 投票:0回答:3

我想检查字典是否包含与键列表中完全相同的键(不多也不少)。我目前正在使用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
python dictionary
3个回答
5
投票

关于什么

set(d) == set(key_list)

@gmds指出,set(d)等于set(d.keys())


0
投票

列表非常适合维护订单,但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)


0
投票

你可以这样做:

>>> d = {'1': 'one', '3': 'three', '2': 'two'}
>>> key_list = ['1', '2', '3']
>>> sorted(d) == sorted(key_list)
True
>>> 
© www.soinside.com 2019 - 2024. All rights reserved.