迭代字数值 [英] Iterating over dict values
本文介绍了迭代字数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我想迭代存储在元组中的字典值。
If i would like to iterate over dictionary values that are stored in a tuple.
我需要返回持有CI值的对象,我假设我需要某种for循环:
i need to return the object that hold the "CI" value, i assume that i will need some kind of a for loop :
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]
在这里,一个参考点是好的。
i am probably missing something here, a point of reference would be good.
如果有一个更快的方式这样做,这将大大有助于
if there is a faster way doing so it would all so help greatly
推荐答案
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..
这可能会解决您的问题。
This might solve your problem.
输出:
>>>
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']
>>>
Hope this is what you want, otherwise first method is already printing all keys, example output:
if x==1 or x=="CI":
>>>
x holding 1.
q holding CI.
q holding 1.
q holding 1.
>>>
这篇关于迭代字数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文