2015-11-04 52 views
-2

假设我有这个名单使用词典:Python列表,以不同的密钥

In [5]: m 

Out[5]: [{0: ['a', 'b'], 1: '1', 2: '2'}, 
     {0: ['a', 'b'], 1: '3', 2: '4'}, 
     {0: ['xx', 'yy'], 1: '100', 2: '200'}, 
     {0: ['xx', 'yy'], 1: '300', 2: '400'}] 

我这样做:

In [6]: r = defaultdict(list) 

In [7]: for k, v in ((k, v) for row in m for k, v in row.iteritems()): 
      r[k].append(v) 

并返回:

In [8]: r 
Out[8]: defaultdict(list, 
     {0: [['a', 'b'], ['a', 'b'], ['xx', 'yy'], ['xx', 'yy']], 
     1: ['1', '3', '100', '300'], 
     2: ['2', '4', '200', '400']}) 

但我想要其他的东西,像这样:

 {0: ['a', 'b'], 
     1: ['1', '3'], 
     2: ['2', '4']}, 

     {0: ['xx', 'yy'], 
     1: ['100', '300'], 
     2: ['200', '400']} 

我该怎么做?我想在关键字0中取相同的值,并收集其他所有在其他关键字中找到的值。

非常感谢!

+1

我不明白你要做的转换。你能一步一步地描述如何从你拥有的东西开始,最终得到你想要的东西吗?它不仅可能让你获得更好的帮助,甚至可以“点击”如何自己做。 –

+0

只将初始列表视为两个单独的列表。你会没事的。 – sobolevn

+0

@sobolevn我不能对待初始列表,因为这是合成数据,对于设置的一种方式,真正的列表有很多键,我不能手动完成。 –

回答

1

第1步 - 先拆分词典,否则,不清楚自动拆分它们的逻辑是什么。 第2步 - 遍历字典列表并应用一些if语句。 这是我认为它应该看起来像。希望我有这个背后的逻辑吧:

d = [{0: ['1', '2'], 1: '3', 2: '4'}, 
    {0: ['1', '2'], 1: '6', 2: '7'}, 
    {0: ['1111', '2222'], 1: '6', 2: '7'}, 
    {0: ['1111', '2222'], 1: '66', 2: '77'} 
    ] 

    #step 1 
    def splitList(l, n): 
     """ 
     takes list and positions to take from the list  
     """ 
     output = [] 
     for p in n: 
      output.append(l[p]) 
     return output 

    #step 2 
    def orgDict(d): 
     """ 
     modifies list of dictionaries into 1 
     """ 
     d_output = {}  
     for d_ind in d:     
      for d_ind2 in d_ind: 
       if (d_output.get(d_ind2) == None): 
        if (type(d_ind[d_ind2]) == list): 
         d_output[d_ind2] = d_ind[d_ind2] 
        else: 
         d_output[d_ind2] = [d_ind[d_ind2]] 
       else: 
        if ((d_ind[d_ind2] not in d_output[d_ind2]) and (d_ind[d_ind2] != d_output[d_ind2])): 
         d_output[d_ind2].append(d_ind[d_ind2]) 
     return d_output 

#tests 
#expected output: 
#{0: ['1', '2'], 1: ['3', '6'], 2: ['4', '7']} 
print orgDict(splitList(d,[0,1])) 

#expected output: 
#{0: ['1111', '2222'], 1: ['6', '66'], 2: ['7', '77']} 
print orgDict(splitList(d,[2,3]))