你可以在python的字典上使用while循环吗?

时间:2017-11-22 20:57:10

标签: python dictionary while-loop

如果我的词典中某个键的值确实满足条件,我想跳出循环并将属性设置为True

我到目前为止所做的是:

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

我是否需要使用for循环并遍历字典中的所有项目,还是可以使用while循环?

5 个答案:

答案 0 :(得分:5)

您不必继续遍历整个字典 - 您可以break离开循环:

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

答案 1 :(得分:3)

在像这样的线性搜索的情况下,循环&打破旗帜是一种经典的技术。将while保留到无法预测循环何时结束的情况。

然而,比设置标志更加pythonic方法(就像我们在Java或C中必须做的那样)将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
但是,只需要我的2美分:迭代字典应该没有中断来处理所有项目。潜在的break意味着在某个地方进行线性搜索,如果数据组织得更好,可能会更快(例如将值存储为其他字典的键,具体取决于您所查找的内容,因此查找速度更快)

答案 2 :(得分:3)

pythonic变体将使用any

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

例如,如果您想检查是否有一对(key, value)的总和大于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

如文档中所述,any相当于:

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

非常看起来像是作为函数编写的代码。

答案 3 :(得分:0)

print(“这是一本字典”) Dict = {“ abase”:“降低位置,估计等;降低。” ,

“修道院”:“女修道院的上级夫人。” ,

“修道院”:“这些建筑物共同构成了僧侣或修女社会的住所。” ,

“住持”:“僧侣社区的上级。” ,

“ abdicate”:“要放弃(皇族力量等)。”

“腹部”:“在哺乳动物中,隔膜和骨盆底之间的内脏腔;腹部。” ,

“腹部”:“属于,关于腹部或位于腹部。” ,

“绑架”:“违背或非法将某人带走。” ,

“ abed”:“在床上;在床上。”,

“ append”:“将某些东西连接到最后”, “ accuracy”:“精确度”。

“准确”:“完全符合真理或标准。”,

“被诅咒”:“沦为邪恶,痛苦或不幸的人。”,

“ accustom”:“通过使用使其熟悉。”,

“ acerbity”:“酸,带有苦涩味。”,

“乙酸盐”:“乙酸盐。”,

“ acetic”:“醋的,关于醋的或与醋有关的。”,

“疼痛”:“要痛苦或痛苦。”,

“ achillean”:“无敌”,

“消色差”:“无色”,

“酸”:“一种酸性物质”。

“酸化”:“要变成酸。”,

“致谢”:“承认;承认其真实性或有效性。”,

“确认”:“识别”。

“ acme”:“最高点或最高点。”,

“声音”:“与行为或听觉有关。”,

“相识”:“使人熟悉或交谈。”,

“默认”:“遵守;提交。”,

“默认”:“被动同意”。

“ acquire”:“获得独立。”,

“获取”:“通常通过努力或劳动获得的任何东西或自己创造的东西。”,

“无罪”:“从指控中释放或清除。”,

“无罪释放”:“通过司法诉讼免于指控。”,

“无罪”:“解除或解除债务,义务或责任。”,

“英亩”:“土地,特别是耕地的数量或范围。”,

“ acrid”:“辛辣或苦涩。”,

“ acrimonious”:“充满痛苦”。 ,

“ acrimony”:“言语或脾气的尖锐或苦涩。” ,

“ actionable”:“冒充冒犯诽谤性言辞的行为的败笔。”,

“事实”:“任何现实。”}

X =(input(“如果您想搜索任何单词,请执行\ n”)) 如果X不在Dict中: exit(“您的单词不在词典中”) 如果X在Dict中: 打印(Dict [X]) 而(True): X =(input(“(如果您想搜索任何单词,请执行\ n”)) 如果X在Dict中: 打印(Dict [X]) 如果X不在Dict中: 打印(“您的单词不在词典中”) 打破 ****#在任何您想复制我的代码的地方运行它,它对我来说效果很好,它是使用while循环制作的,请随时使用它


答案 4 :(得分:-1)

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