Iterating over dict values

为君一笑 提交于 2019-12-18 14:52:13

问题


If i would like to iterate over dictionary values that are stored in a tuple.

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


回答1:


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.

Output:

>>> 
q holding CI.
>>> 

Edit for your comment:

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"))

Output:

>>> 
['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.
>>> 



回答2:


Ways to iterate over a dictionary

First things first, there are a few ways you can loop over a dictionary.

Looping directly over the dictionary:

>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)}
>>> for key in z:
...     print key,
...
'x' 'z'

Notice that the loop variables that get returned when you just loop over a dictionary are the keys, not the values associated with those keys.

Looping over the values of a dictionary:

>>> 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)

Looping over both the keys and the values:

>>> 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)

The latter two are somewhat more efficient than looping over keys and running z[key] to obtain the value. It's also arguably more readable.

Building on these...

List Comprehensions

List comprehensions are great. For the simple case of searching for just 'CI':

>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)}
>>> [key for key, value in z.items() if 'CI' in value]
['z']

For finding dict keys that hold several search items:

>>> 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']

For finding dict keys that hold any of multiple search items:

>>> 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']

If the latter two look a bit too complex as one-liners, you can re-write the last bit as a separate function.

>>> 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']

Once you get used to the [x for x in iterable if condition(x)] syntax, the format should be very easy to read and follow.




回答3:


try this:

>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)}
>>> list(filter(lambda x:'CI' in z.get(x),z))
['z']



回答4:


z = {'x':(123,"SE",2,1),'q':(124,"CI",1,1)}
for key, val in z.items():
    if 'CI' in val:
        return z[key]



回答5:


There's no need to retrieve the key if you're only interested in the values:

In 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

In 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


来源:https://stackoverflow.com/questions/27733685/iterating-over-dict-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!