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