簡體   English   中英

在While循環中打印字典

[英]Printing dictionary in a While Loop

我一直在環顧四周,看看是否有人確實做到了,但是找不到,所以希望我能在這里得到一些幫助。

newDict = {'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':30}

我創建了這個字典,我想使用while循環以這種方式輸出它:

Jan 31
Feb 29
Mar 31
Apr 30
May 31
Jun 30
Jul 31
Aug 30

我能夠使用for循環來做到這一點,只是很好奇如何使用while循環來完成它。

您可以將字典iteritems調用iteritemsiterator (Python 2.x),或對items() iter (Python 3.x)

# Python 2.x
from __future__ import print_function
items = newDict.iteritems()

# Python 3.x
items = iter(newDict.items())

while True:
    try: 
        item = next(items)
        print(*item)
    except StopIteration:
        break

注意:我們將在Python 2.x上導入print_function ,因為print將是語句而不是函數,因此print(*item)行實際上將失敗

這是使用.pop方法的另一個選項。

newDict = {
    'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 
    'May':31, 'Jun':30, 'Jul':31, 'Aug':30
}
t = newDict.items()
while t:
    print '%s %d' % t.pop()

典型輸出

Jul 31
Jun 30
Apr 30
Aug 30
Feb 29
Mar 31
May 31
Jan 31

該代碼不會修改newDict的內容,因為在Python 2中, dict.items()創建了字典的(鍵,值)對的列表。 在Python 3中,它會返回一個動態View對象,該對象沒有.pop方法,因此該代碼無法在其中運行。

請記住, dict是無序集合,因此輸出順序可能不是您期望的。

使用以下代碼:

key=list(newDict.keys())
i=0
while i<len(key):
    print(key[i]," ",newDict[key[i]])
    i+=1

您可以使用while循環執行此操作。

newDict = {'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':30}
i = 0
while i < len(newDict):
    val = newDict.items()[i]
    print val[0], val[1]
    i += 1

這是一個荒謬的要求,但這是實現它的一種方法:

newDict = {'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':30}

while newDict:
  x = next(x for x in newDict)
  print(x, newDict.pop(x))

警告:

while執行完畢后, newDIct將為

您可以使用iterator

Python 2.7

new_dict = {'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':30}
a = iter(new_dict.iteritems())
default = object()

while a:
    elem = next(a, default)
    # This check is to know whether iterator is exhausted or not.
    if elem is default:
        break
    print "{} {}".format(*elem)

Python 3

new_dict = {'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':30}
a = iter(new_dict.items())
default = object()

while a:
    elem = next(a, default)
    # This check is to know whether iterator is exhausted or not.
    if elem is default:
        break
    print("{} {}".format(*elem))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM