遍历python默认字典

时间:2019-03-20 10:46:50

标签: python python-3.x

我在代码中创建一个默认字典,如下所示:

  

defaultdict(<class 'list'>,{'month':['JAN','FEB'],'car':['baleno','santro'],'measure':['sales','费用”]})

cube = 'test'

现在,我想通过添加变量cube以以下格式打印上述字典:

  

['month','JAN','car','baleno','measure','sales','test']

     

['month','JAN','car','baleno','measure','expense','test']

     

['month','JAN','car','santro','measure','sales','test']

     

['month','JAN','car','santro','measure','expense','test']

     

['month','FEB','car','baleno','measure','sales','test']

     

['month','FEB','car','baleno','measure','expense','test']

     

['month','FEB','car','santro','measure','sales','test']

     

['month','FEB','car','santro','measure','expense','test']

我实际上正在使用三个循环来实现上述输出,但是想要获得一个整洁的循环。

dim=['month','car','measure']
cube='test'
for b in itertools.product(*(k.values())):                                                  
        list1 = list()                                      
        for (f, c) in zip(b, dim):                                                         
            list1.append(c)                                 
            list1.append(f)                                 
        list1.append(cube)                             
        print(list1) 

k 是默认字典

PS:我是PYTHON的新手。只需使用几个月。

1 个答案:

答案 0 :(得分:0)

鉴于输入是字典,我认为您不会比嵌套for循环更高效(请注意:itertools.product等效于for循环)。您可以使用列表理解功能将其作为一个衬纸来完成,但这不会更有效,而且可读性也较低。

您的实现看起来不错,这是简化的写法:

k = {'month': ['JAN', 'FEB'], 
     'car': ['baleno', 'santro'], 
     'measure': ['sales', 'expense']}

# Grab the keys from the dictionary as opposed to hard-coding them
dim=k.keys()
cube='test'

# cartesian product of each key's set of values
for b in itertools.product(*k.values()):                                                
    list1 = list()
    # extending empty list by (key, value) for specific values in product b                         
    for pair in zip(dim, b):                                                         
        list1.extend(pair)                                 
    list1.append(cube)                             
    print(list1)