在Python中能否使用while循环遍历字典?

7
如果我的字典中某个键的值满足条件,我希望跳出循环并将一个属性设置为True
目前我的做法是:
fooBar = False
for key, value in my_dict.items():
    if (condition):
        fooBar = True

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


2
一个 while 循环如何知道何时结束?为什么不直接跳出 for 循环呢?如果你有一个布尔标志,那为什么不使用 else 从句呢? - Ignacio Vazquez-Abrams
3
fooBar = True 之后尝试使用 break - NendoTaka
1
当然可以使用 while 循环,如果你真的有某些原因必须这样做,那么每个 for 循环都可以写成 while 循环,但我并不认为它比你的 for 循环更有优势。 - juanpa.arrivillaga
可能有更好的方法来完成这个任务。如果条件取决于键和值,您可以使用集合方法选择子集项,以便在条件为真之前不需要循环遍历所有项。这是有效的,因为.keys()返回类似集合的视图,如果值是适当的类型,则.items()视图也是类似集合的。 - PM 2Ring
@PM2Ring 这只适用于Python 3。但是谁还在2017年使用Python 2呢? :) 我同意对字典进行迭代时应该不使用break来处理所有项。潜在的break意味着某个地方存在线性搜索,如果数据组织得更好,则可能会更快。 - Jean-François Fabre
@Jean-FrançoisFabre 没错。 :) 我们应该假设所有关于Python的问题都是关于Python 3的,除非OP明确提到其他版本。然而,Python 2.6+确实提供了View objects,但它们的名称为.viewkeys()等。 - PM 2Ring
7个回答

7

你不必继续迭代整个字典 - 你可以在循环中使用break关键字来跳出循环:

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

2
问题是是否可以使用while循环遍历字典。提供的答案没有回答这个问题,而是提供了一种替代方法(for + break)。“while”语句与“for”语句背后的一个主要思想是它允许退出循环而不需要控制流跳转(无需break)。 - rauldg

6

如果使用Python语言,更加推荐使用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

这看起来非常像你编写的函数代码。


良好的评价。但它不适用于复杂的处理。 - Jean-François Fabre
@Jean-FrançoisFabre:为什么不呢?any(complex_processing(k, v) for k, v in my_dict.items()) - Eric Duminil
1
我的意思是一些带有辅助变量、累积操作的代码...在函数中不太好实现,因为你需要使用全局变量(注意:我给你的答案点了赞)。 - Jean-François Fabre

4
在像这样的线性搜索情况下,设置标志并循环中断是一种经典技术。将while保留给无法预测循环何时结束的情况。
然而,比在Java或C中设置标志更符合Python风格的方法是在for循环中使用else
for key, value in my_dict.items():
    if condition:
        break
else:
   # here we know that the loop went to the end without a break

仅代表个人观点:遍历字典时应该不使用break,以处理所有项目。潜在的break意味着某处存在线性搜索,如果数据组织得更好(例如,将值存储为其他字典的键,具体取决于您要查找的内容,因此查找更快),则速度可能会更快。


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

你可以尝试在字典上使用items()方法。

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

1

是的,我们肯定可以在Python中使用while循环来迭代字典。

这是一个字典的例子

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

使用while循环遍历字典

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

通过将整个字典转换为列表,我们可以使用while循环通过索引位置进行迭代

使用while循环遍历字典键和值

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

通过将字典的键和值转换为列表,您可以使用while循环通过索引位置迭代字典的键和值。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接