简体   繁体   English

如何使用for循环将存储在字典中的变量打印到屏幕上?

[英]How can I print a variables stored in a dictionary to screen using a for loop?

I have two dictionaries as follows: 我有两个字典,如下所示:

superhero_dict  = {
    u'phone_number_4': u'07400000000', 
    u'phone_number_3': u'02000000000', 
    u'phone_number_2': u'02010000000', 
    u'phone_number_1': u'07500000000', 
    u'full_name': u'Bruce Wayne'
}

superhero_dict =    {
    u'phone_number_3': u'02000000001', 
    u'phone_number_2': u'02010000001', 
    u'phone_number_1': u'07500000001', 
    u'full_name': u'Peter Parker',
    u'secret_name': u'Spiderman'
}

I would like to have a for loop that prints the phone numbers of each superhero to screen. 我想要一个for循环,将每个超级英雄的电话号码打印到屏幕上。 The complication is that each dictionary has a different number of (a) keys and (b) phone numbers. 复杂的是,每个词典都有不同数量的(a)键和(b)电话号码。 The format of the phone number key is consistent ie "phone_number_" + integer as shown in the examples. 电话号码密钥的格式是一致的,即示例中所示的“ phone_number _” +整数。

The best I could come up with was 我能想到的最好的是

for secret_number in range(1,10):
    try:
        print superhero_dict["phone_number_"+str(secret_number)]
    except:
        break

There are two issues with this approach: 这种方法有两个问题:

  1. I don't want to use some arbitrary upper limit (10 in the above example) 我不想使用任意上限(在上面的示例中为10)

  2. It doesn't seem very elegant/pythonic 看起来不是很优雅/ pythonic

You can tweak it so there's no limit: 您可以对其进行调整,因此没有限制:

import itertools

for num in itertools.count(1): # count up from 1 infinitely
    phone = superhero_dict.get('phone_number_' + str(num))
    if phone is None:
        break
    print phone

You can use a simple comprehension; 您可以使用简单的理解;

print '\n'.join(superhero_dict[x] for x in superhero_dict 
                                  if x.startswith("phone_number"))

EDIT: In case you didn't see it, check nneonneo's comment above, the better structure will make it even easier/more obvious. 编辑:如果您没有看到它,请查看上面的nneonneo评论,更好的结构将使其更加容易/更加明显。

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

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