Valdas
Valdas

Reputation: 370

Check value in dictionary of dictionaries

foob = {1:{'url':'www.abc.com', 'name':'abc'}, 2:{'url':'www.def.com', 'name':'def'}}
item = {'url':'www.abc.com', 'name':'wrong name'}

if item in foob.values():
    print 'yes'
else:
    print 'no'

I want to change item in list.values() so that it only compares url values and not whole dictionary. Is it possible to do that without iterating through whole dictionary there a simple way to do this without writing a separate for loop?

Upvotes: 0

Views: 67

Answers (2)

Andy Cheung
Andy Cheung

Reputation: 125

I think this code will work, but I don't think there is a way can avoid some kind of iterate.

dict = {1:{'url':'www.abc.com', 'name':'abc'}, 2:{'url':'www.def.com', 'name':'def'}}
item = {'url':'www.abc.com', 'name':'wrong name'}

if item['url'] in [i['url'] for i in dict.values()]:
    print 'yes'
else:
    print 'no'

I agree deceze's code, use any

Upvotes: 0

deceze
deceze

Reputation: 522024

Use any and a generator expression:

if any(i['url'] == item['url'] for i in dict.values()):
    print 'yes'
else:
    print 'no'

Upvotes: 2

Related Questions