Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use a while loop on a dictionary in python?

If a value for one of the keys in my dictionary does satisfies a condition, I want to break out of the loop and set a property to True.

what I'm doing so far is:

fooBar = False
for key, value in my_dict.items():
    if (condition):
        fooBar = True

Do I need to use a for loop and iterate through all items in the dictionary, or can I use a while loop?

like image 802
Nicolae Stroncea Avatar asked Nov 22 '17 20:11

Nicolae Stroncea


People also ask

How do you iterate over a dictionary key?

In order to iterate only over keys you need to call keys() method that returns a new view of the dictionary's keys.

Can you use LEN () on a dictionary?

To calculate the length of a dictionary, we can use the Python built-in len() method. The len() method returns the number of keys in a Python dictionary.

Can you put a while loop in a function Python?

Answer. Yes, you can use a function call in the while expression. If calling only a function in the expression, it should return True or False . If the function is part of a more complex expression, then the end result of the expression should evaluate to True or False .

When should you not use a dictionary Python?

Python dictionaries can be used when the data has a unique reference that can be associated with the value. As dictionaries are mutable, it is not a good idea to use dictionaries to store data that shouldn't be modified in the first place.


1 Answers

You don't have to continue iterating over the entire dictionary - you could just break out of the loop:

fooBar = False
for key, value in my_dict.items():
    if (condition):
        fooBar = True
        break # Here! 
like image 152
Mureinik Avatar answered Oct 20 '22 03:10

Mureinik