简体   繁体   English

Python:迭代字典中的字典

[英]Python: Iterating through dictionaries within dictionaries

I have this test dictionary: 我有这个测试词典:

addressBook = {'a' : {'Name' : 'b', 'Address' : 'c', 'PhoneNo' : '5'}, 'd' : {'Name' : 'e', 'Address' : 'f', 'PhoneNo' : '7'}}

I want to iterate through each dictionary within addressBook and display each value (name, address and phoneno). 我想遍历addressBook中的每个字典并显示每个值(名称,地址和phoneno)。

I have tried this: 我试过这个:

for x in addressBook:
    for y in x:
        print(y, "\t", end = " ")

However, this only prints the key of each dictionary (ie 'a' and 'b'). 但是,这只打印每个字典的键(即'a'和'b')。

How do I display all the values? 如何显示所有值?

Whenever you iterate through a dictionary by default python only iterates though the keys in the dictionary. 每当你默认迭代字典时,python只会迭代字典中的

You need to use either the itervalues method to iterate through the values in a dictionary, or the iteritems method to iterate through the (key, value) pairs stored in that dictionary. 您需要使用itervalues方法迭代字典中的值,或使用iteritems方法迭代存储在该字典中的(key, value)对。

Try this instead: 试试这个:

for x in addressBook.itervalues():
    for key, value in x.iteritems():
        print((key, value), "\t", end = " ")

I would do something like this 我会做这样的事情

for k1,d in addressBook.items:
   for k2,v2 in d.items:
      print("{} :: {}".format(k2, v2))

However if all you want is to print the dictionary neatly, I'd recommend this 但是如果你想要的只是整齐地打印字典,我会推荐这个

   import pprint
   s = pprint.pformat(addressBook)
   print(s)

Iterating over a dictionary only gives you the dictionary keys, not the values. 迭代字典只能为您提供字典键,而不是值。 If you want just the values, then use this: 如果你只想要这些值,那么使用:

for x in addressBook.values()

Alternatively, if you want both keys and values, use iteritems() like this: 或者,如果您想要键和值,请使用iteritems(),如下所示:

for key,value in addressBook.iteritems():
        print key, value

Issue with your code: 您的代码问题:

for x in addressBook:  # x is key from the addressBook dictionary.
    #- x is key and type of x is string. 
    for y in x:       # Now we iterate every character from the string.
        print(y, "\t", end = " ")  # y character is print

Try following: 试试以下:

for i in addressBook:
    print "Name:%s\tAddress:%s\tPhone:%s"%(addressBook[i]["Name"], addressBook[i]["Address"], addressBook[i]["PhoneNo"])


Name:b  Address:c   Phone:5
Name:e  Address:f   Phone:7

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

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