Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a dictionary has exact same keys in a list

I want to check if a dictionary contains the exact same keys as in a list of keys (no more, no less). I'm currently using all() and a length check to do this. Is there a better way? Thanks!

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
like image 472
qshng Avatar asked Dec 09 '25 09:12

qshng


1 Answers

What about

set(d) == set(key_list)

set(d) is equals to set(d.keys()) as @gmds pointed out

like image 132
Ursus Avatar answered Dec 10 '25 22:12

Ursus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!