如何在迭代它时只打印字典中元组元素值的值

时间:2018-02-11 05:05:50

标签: python dictionary iteration

d = {'k1':1,'k2':[(2,4),(6,8),(10,12)],'k3':3}

for (a,b) in d.values():
    print (a)
    print (b)

当我尝试这个时它会说

TypeError                                 Traceback (most recent call last)
 <ipython-input-49-81a0566d1778> in <module>()
  ----> 1 for (a,b) in d.values():
  2     print (b)
  3     print (a)

 TypeError: 'int' object is not iterable

我只想将输出打印为

2

4

6

8

10

12

2 个答案:

答案 0 :(得分:1)

由于您的字典包含元组列表(您想要展平)和整数:

d = {'k1':1,'k2':[(2,4),(6,8),(10,12)],'k3':3}

在展平列表之前,必须首先检查类型,然后循环遍历其内容:

for (key, value) in d.items():
    if type(value) is list:
        # flatten the list of tuples into a list of ints
        # by applying `itertools.chain` on the unpacked (*) list
        # of tuples
        flattened = itertools.chain(*d[key])
        for num in flattened:
            print(num)

注意:要展平列表,您需要导入itertools,解压缩工作在Python 2.7+和Python 3中。

答案 1 :(得分:0)

# for key,val in d.items(): # python 3 version
for key,val in d.iteritems(): # go through all of key, values of d
    if isinstance(val, list): # check if they are a list/array
        for tup in val: # if they are, go through all of them
            if isinstance(tup, tuple):
                for num in tup: # don't assume they are all 2 number tuples
                    print("{0}\n".format(num)) # print each with an extra new line

您假设所有dict值都是元组。尝试减少对它们的关注,并确保检查它们的类型。通过确保它是一个列表,您可以知道您可以遍历列表。之后确保列表中的所有元素都是元组,然后遍历元组中的所有数字并打印(这也允许您打印具有2个以上数字的元组。