Can you use a while loop on a dictionary in python?
Asked Answered
M

7

8

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?

Marzipan answered 22/11, 2017 at 20:57 Comment(6)
How would a while loop know when to end? Why wouldn't you just break out of the for loop? If you have a boolean flag then why wouldn't you just use the else clause instead?Herbivore
Try using a break after fooBar = TrueCastled
Sure you can use a while loop, every for loop can be written as a while loop if you really have to for some reson but I don't see any advantages over your for loop.Arms
There may be better ways to do this. If the condition depends on the key as well as the value you may be able to use set methods to select a subset of the items so that you don't need to loop over them all until the condition is true. This is efficient because .keys() returns a set-like View, and if the values are of a suitable type then the .items() View is also set-like.Atlas
@PM2Ring that is true in python 3 only. But who uses python 2 in 2017 ? :) I agree that iterating on a dict should be done without break to process all items. a potential break means that there's a linear search somewhere that could be faster if the data was organized better.Nozzle
@Jean-FrançoisFabre Exactly. :) We should assume that all Python questions are about Python 3 unless the OP explicitly mentions otherwise. However, Python 2.6+ does provide View objects, but they're named .viewkeys() etc.Atlas
B
7

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! 
Benzel answered 22/11, 2017 at 20:59 Comment(1)
The question is if it is possible to loop a dictionary with while. And the provided answer instead of answering that, provides an alternative (for + break). One main idea behind the "while" statement as opposed to the "for" statement is that it allows a exit of the loop without control flow jump (no break).Chronograph
T
7

The pythonic variant would be to use any:

any(condition for k, v in my_dict.items())

As an example, if you want to check if there's any pair of (key, value) with a sum larger than 10:

>>> my_dict = {1: 4, 5: 6}
>>> any(k + v > 10 for k, v in my_dict.items())
True
>>> any(k + v > 100 for k, v in my_dict.items())
False

As mentioned in the documentation, any is equivalent to:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

which very much looks like your code written as a function.

Tribadism answered 22/11, 2017 at 21:2 Comment(3)
good remark. It doesn't apply to a complex processing though.Nozzle
@Jean-FrançoisFabre: Why not? any(complex_processing(k, v) for k, v in my_dict.items())Tribadism
I mean some code with auxiliary variables, cumulative stuff... not very good in a function since you'd have to use globals (note: I upvoted your answer)Nozzle
C
4

In the case of linear search like this, looping & breaking with a a flag set is a classical technique. Reserve while to cases where you cannot predict when the loop is going to end at all.

However, a more pythonic method than setting a flag (like we'd have to do in Java or C) would be to use else for the for loop.

for key, value in my_dict.items():
    if condition:
        break
else:
   # here we know that the loop went to the end without a break

just my 2 cents, though: iterating on a dictionary should be done without break to process all items. a potential break means that there's a linear search somewhere that could be faster if the data was organized better (for instance with values stored as keys to other dictionaries depending on what you're looking for so lookup is faster)

Coadjutrix answered 22/11, 2017 at 21:2 Comment(0)
P
1
print("It is a dictionary")
dt = {
    "abase" : "To lower in position, estimation, or the like; degrade." ,
    "abbess" : "The lady superior of a nunnery." ,
    "abbey" : "The group of buildings which collectively form the dwelling-place of a society of monks or nuns." ,
    "abbot" : "The superior of a community of monks." ,
    "abdicate" : "To give up (royal power or the like).",
    "abdomen" : "In mammals, the visceral cavity between the diaphragm and the pelvic floor;the belly." ,
    "abdominal": "Of, pertaining to, or situated on the abdomen." ,
    "abduction" : "A carrying away of a person against his will, or illegally." ,
    "abed" :"In bed; on a bed.",
    "append":"To join something to the end",
    "accuracy" :  "Exactness.",
    "accurate" : "Conforming exactly to truth or to a standard.",
    "accursed" :  "Doomed to evil, misery, or misfortune.",
    "accustom": "To make familiar by use.",
    "acerbity" : "Sourness, with bitterness and astringency.",
    "acetate" : "A salt of acetic acid.",
    "acetic" : "Of, pertaining to, or of the nature of vinegar.",
    "ache": "To be in pain or distress.",
    "achillean" : "Invulnerable",
    "achromatic" : "Colorless",
    "acid" : "A sour substance.",
    "acidify" : "To change into acid.",
    "acknowledge":  "To recognize; to admit the genuineness or validity of.",
    "acknowledgment":"Recognition.",
    "acme" : "The highest point, or summit.",
    "acoustic" : "Pertaining to the act or sense of hearing.",
    "acquaint" : "To make familiar or conversant.",
    "acquiesce" : "To comply; submit.",
    "acquiescence" : "Passive consent.",
    "acquire" : "To get as one's own.",
    "acquisition" :"Anything gained, or made one's own, usually by effort or labor.",
    "acquit" : "To free or clear, as from accusation.",
    "acquittal" :  "A discharge from accusation by judicial action.",
    "acquittance": "Release or discharge from indebtedness, obligation, or responsibility.",
    "acreage" : "Quantity or extent of land, especially of cultivated land.",
    "acrid" :"Harshly pungent or bitter.",
    "acrimonious" : "Full of bitterness." ,
    "acrimony" : "Sharpness or bitterness of speech or temper." ,
    "actionable" :"Affording cause for instituting an action, as trespass, slanderous words.",
    "actuality" : "Any reality."
}

X = (input("If you wanna search any word then do\n"))
if X not in dt:
    exit("Your word is out of dictionary")
if X in dt:
    print(dt[X])
    while (True):
        X = (input("If you wanna search any word then do\n"))
        if X in dt:
            print(dt[X])
        if X not in dt:
            print("Your word is out of dictionary")
            break

#Run it anywhere you want copy my code it works fine with me it is made using while loop so feel free to use it
Pasho answered 5/5, 2020 at 9:3 Comment(0)
L
1
my_dict = {"a": 12, "b", 43, "c": 5"}
comp = my_dict.items() # [("a", 12), ("b", 43), ("c", 5)]
i = 0
while True:
    # some code
    current = comp[i]
    i += 1

you can try using items() method on your dictionary

Lesleelesley answered 11/2, 2022 at 9:25 Comment(0)
N
1

Yes we can definitely use while loop for iterating through a Dictionary in Python.

This is the example of a Dictionary

d = {1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216, 7: 343, 8: 512, 9: 729, 10: 1000}

Iterating through the Dictionary using while loop

dl = list(d)
i = 0
while i<len(d):
print(dl[i])
i+=1

By converting the entire dictionary into a list, we can iterate using while loop through index position

Iterating through Dictionary keys as well as values using while loop

k = list(d.keys())
v = list(d.values())
i = 0
while i<len(d):
print(k[i],' ',v[i])
i+=1

By converting the dictionary keys and values into list, you can use while loop to iterate through the dictionary keys as well as values through index position

Northwest answered 24/4, 2023 at 11:47 Comment(0)
P
0
print("It is a dictionary")
Dict = {"abase" : "To lower in position, estimation, or the like; degrade." ,

"abbess" : "The lady superior of a nunnery." ,

"abbey" : "The group of buildings which collectively form the dwelling-place of a society of monks or nuns." ,

"abbot" : "The superior of a community of monks." ,

"abdicate" : "To give up (royal power or the like).",

"abdomen" : "In mammals, the visceral cavity between the diaphragm and the pelvic floor;the belly." ,

"abdominal": "Of, pertaining to, or situated on the abdomen." ,

"abduction" : "A carrying away of a person against his will, or illegally." ,

"abed" :"In bed; on a bed.",

"append":"To join something to the end",
"accuracy" :  "Exactness.",

"accurate" : "Conforming exactly to truth or to a standard.",

"accursed" :  "Doomed to evil, misery, or misfortune.",

"accustom": "To make familiar by use.",

"acerbity" : "Sourness, with bitterness and astringency.",

"acetate" : "A salt of acetic acid.",

"acetic" : "Of, pertaining to, or of the nature of vinegar.",

"ache": "To be in pain or distress.",

"achillean" : "Invulnerable",

"achromatic" : "Colorless",

"acid" : "A sour substance.",

"acidify" : "To change into acid.",

"acknowledge":  "To recognize; to admit the genuineness or validity of.",

"acknowledgment":"Recognition.",

"acme" : "The highest point, or summit.",

"acoustic" : "Pertaining to the act or sense of hearing.",

"acquaint" : "To make familiar or conversant.",

"acquiesce" : "To comply; submit.",

"acquiescence" : "Passive consent.",

"acquire" : "To get as one's own.",

"acquisition" :"Anything gained, or made one's own, usually by effort or labor.",

"acquit" : "To free or clear, as from accusation.",

"acquittal" :  "A discharge from accusation by judicial action.",

"acquittance": "Release or discharge from indebtedness, obligation, or responsibility.",

"acreage" : "Quantity or extent of land, especially of cultivated land.",

"acrid" :"Harshly pungent or bitter.",

"acrimonious" : "Full of bitterness." ,

"acrimony" : "Sharpness or bitterness of speech or temper." ,

"actionable" :"Affording cause for instituting an action, as trespass, slanderous words.",

"actuality" : "Any reality."}

X = (input("If you wanna search any word then do\n"))
if X not in Dict:
    exit("Your word is out of dictionary")
if X in Dict:
    print(Dict[X])
    while (True):
        X = (input("If you wanna search any word then do\n"))
        if X in Dict:
            print(Dict[X])
        if X not in Dict:
            print("Your word is out of dictionary")
            break
****#Run it anywhere you want copy my code it works fine with me****
Pasho answered 5/5, 2020 at 9:0 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.