2016-11-11 100 views
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' 

我想更改item in list.values(),以便它只比较url值而不是整个字典。是 有可能做到这一点,而无需遍历整个字典 有一个简单的方法来做到这一点,而无需编写一个单独的for循环?检查字典字典中的值

+1

迭代是唯一的选择,尝试将其转换成其他一些结构如列表等,那么你实现你想要的结果,但仍然是一个复杂的过程。 –

+1

即使'在'迭代幕后名单...! – deceze

+1

是的,无论如何你需要迭代。 –

回答

2

使用any和发电机的表达:

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

我不能使用任何somewhy,它在Eclipse中工作,但我为Plex编写一个插件,并且在那里我得到了'NameError:全局名'any'没有定义'并不知道为什么... – Valdas

+0

快速谷歌搜索修复这个:) http://stackoverflow.com/questions/9037821/python-nameerror-global-name-any-is-not-defined – Valdas

0

我认为这段代码可以工作,但我不认为有一种方法可以避免某种迭代。

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' 

我同意deceze的代码,使用任何

+0

这是非常浪费的做法。 – deceze

+0

@deceze请详细说明 – Valdas

+0

@deceze你的意思是,除了这个事实,它重新定义了'dict'内置函数? –