Python的字典列表将值附加到不同的键

时间:2015-11-04 21:49:42

标签: python dictionary

假设我有这个带字典的列表:

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 :(得分: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]))