Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over dict values

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

like image 764
Mike.G Avatar asked Jan 01 '15 19:01

Mike.G


People also ask

Can you iterate over a dictionary in Python?

You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.

What are the two important methods of dictionary to iterate with key and values of dictionary?

Using a for loop and the items() method you can iterate over all of the keys and values in a list.

How do you compare values in a dictionary?

Python List cmp() Method. The compare method cmp() is used in Python to compare values and keys of two dictionaries. If method returns 0 if both dictionaries are equal, 1 if dic1 > dict2 and -1 if dict1 < dict2.


2 Answers

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.

like image 70
zehnpaard Avatar answered Oct 09 '22 20:10

zehnpaard


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.
>>> 
like image 23
GLHF Avatar answered Oct 09 '22 20:10

GLHF