0
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?

Valdas
  • 368
  • 4
  • 14
  • 1
    Iteration is the only choice, try converting it into some other structure like lists etc then you achieve your desired result but still that one is also a complex process. – Sunil Lulla Nov 11 '16 at 08:59
  • 1
    Even `in` iterates the list behind the scenes…! – deceze Nov 11 '16 at 09:00
  • 1
    Yes it is, in any way you need Iterations. – Sunil Lulla Nov 11 '16 at 09:01
  • 2
    Please, don't overwrite built-in functions. There's a `dict` built-in function, which is actually the dictionaries constructor, and is useful when copying dictionaries. If you call `dict({})' after your declaration, you're gonna have a surprise... – Right leg Nov 11 '16 at 09:10
  • 2
    Also, you are using a dictionary, but if your keys are only successive integers, it's more than useless, and you should use a list instead. – Right leg Nov 11 '16 at 09:15

2 Answers2

2

Use any and a generator expression:

if any(i['url'] == item['url'] for i in dict.values()):
    print 'yes'
else:
    print 'no'
deceze
  • 510,633
  • 85
  • 743
  • 889
  • I can't use any somewhy, it works in Eclipse, but I am coding a plugin for Plex and in there I get `NameError: global name 'any' is not defined` and do not know why... – Valdas Nov 11 '16 at 09:31
  • Quick googling fixed this :) http://stackoverflow.com/questions/9037821/python-nameerror-global-name-any-is-not-defined – Valdas Nov 11 '16 at 09:36
0

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

Andy Cheung
  • 125
  • 6