简体   繁体   English

你能在 python 中的字典上使用 while 循环吗?

[英]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 .如果我字典中某个键的值确实满足条件,我想跳出循环并将属性设置为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?我需要使用 for 循环遍历字典中的所有项目,还是可以使用 while 循环?

You don't have to continue iterating over the entire dictionary - you could just break out of the loop:您不必继续遍历整个词典-你可以只break循环了:

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

The pythonic variant would be to use any : pythonic 变体将使用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:例如,如果您想检查是否存在总和大于 10 的(key, value)对:

>>> 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:如文档中所述, any等效于:

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.在像这样的线性搜索的情况下,使用 aa 标志集进行循环和中断是一种经典技术。 Reserve while to cases where you cannot predict when the loop is going to end at all.while保留用于您根本无法预测循环何时结束的情况。

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.然而,比设置标志(就像我们必须在 Java 或 C 中做的那样)更 Pythonic 的方法是将else用于for循环。

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.不过,只有我的 2 美分:迭代字典应该不间断地处理所有项目。 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)潜在的break意味着如果数据组织得更好,某处的线性搜索可能会更快(例如,根据您要查找的内容,将值存储为其他字典的键,因此查找速度更快)

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您可以尝试在字典上使用 items() 方法

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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