简体   繁体   中英

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?

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! 

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.

In the case of linear search like this, looping & breaking with aa 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)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM