如果我想迭代存储在元组中的字典值。
我需要返回持有" CI"的对象。值,我假设我需要某种for循环:
z = {'x':(123,SE,2,1),'z':(124,CI,1,1)}
for i, k in db.z:
for k in db.z[i]:
if k == 'CI':
return db.z[k]
我可能在这里遗漏了一些东西,一个参考点会很好。
如果有更快的方式这样做,那将非常有帮助
答案 0 :(得分:27)
首先,有几种方法可以循环遍历字典。
直接在字典上循环:
>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)}
>>> for key in z:
... print key,
...
'x' 'z'
请注意,循环遍历字典时返回的循环变量是键,而不是与这些键关联的值。
循环使用字典的值:
>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)}
>>> for value in z.values(): # Alternatively itervalues() for memory-efficiency (but ugly)
... print value,
...
(123,'SE',2,1) (124,'CI',1,1)
循环键和值:
>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)}
>>> for key, value in z.items(): # Again, iteritems() for memory-efficiency
... print key, value,
...
'x' (123,'SE',2,1) 'z' (124,'CI',1,1)
后两者比循环键和运行z [key]获得值更有效。它也可以说更具可读性。
建立在这些......
List comprehensions很棒。 对于仅搜索CI'
的简单情况>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)}
>>> [key for key, value in z.items() if 'CI' in value]
['z']
用于查找包含多个搜索项的dict键:
>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)}
>>> search_items = ('CI', 1) # Only keys that hold both CI and 1 will match
>>> [key for key, value in z.items() if all(item in value for item in search_items)]
['z']
用于查找包含多个搜索项目的dict键:
>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)}
>>> search_items = ('CI', 'SE', 'JP') # Keys that hold any of the three items will match
>>> [key for key, value in z.items() if any(item in value for item in search_items)]
['x', 'z']
如果后两者看起来有点过于复杂,那么你可以将最后一位重写为一个单独的函数。
>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)}
>>> search_items = ('CI', 'SE', 'JP') # Keys that hold any of the three items will match
>>> def match_any(dict_value, search_items):
... return any(item in dict_value for item in search_items)
...
>>> [key for key, value in z.items() if match_any(value, search_items)]
['x', 'z']
一旦习惯了[x for x for iterable if condition(x)]语法,该格式应该非常容易阅读和遵循。
答案 1 :(得分:13)
z = {'x':(123,"SE",2,1),'q':(124,"CI",1,1)}
for i in z.keys(): #reaching the keys of dict
for x in z[i]: #reaching every element in tuples
if x=="CI": #if match found..
print ("{} holding {}.".format(i,x)) #printing it..
这可能会解决您的问题。
输出:
>>>
q holding CI.
>>>
编辑您的评论:
def func(*args):
mylist=[]
z = {'x':(123,"SE",2,1),'q':(124,"CI",1,1)}
for x,y in z.items():
for t in args:
if t in y:
mylist.append(x)
return mylist
print (func(1,"CI"))
输出:
>>>
['q', 'q', 'x']
>>>
希望这是你想要的,否则第一种方法已经打印了所有键,例如输出:
if x==1 or x=="CI":
>>>
x holding 1.
q holding CI.
q holding 1.
q holding 1.
>>>
答案 2 :(得分:2)
试试这个:
>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)}
>>> list(filter(lambda x:'CI' in z.get(x),z))
['z']
答案 3 :(得分:1)
z = {'x':(123,"SE",2,1),'q':(124,"CI",1,1)}
for key, val in z.items():
if 'CI' in val:
return z[key]
答案 4 :(得分:0)
如果您只对值感兴趣,则无需检索密钥:
在Python 2.x中:
z = {'x':(123,"SE",2,1),'q':(124,"CI",1,1)}
for value in z.itervalues():
if 'CI' in value:
return value
在Python 3.x中:
z = {'x':(123,"SE",2,1),'q':(124,"CI",1,1)}
for value in z.values():
if 'CI' in value:
return value