如何加入一些dicts?

时间:2013-11-09 08:24:09

标签: python

有人可以帮助我改变这个:

a = [{'one': 4, 'name': 'value1', 'two': 25}, {'one': 2, 'name': 'value1', 'two': 18}, {'one': 1, 'name': 'value1', 'two': 15}, {'one': 2, 'name': 'value2', 'two': 12}, {'one': 1, 'name': 'value2', 'two': 10}]

这样的事情:

b = [{'value1': [(4, 25), (2, 18), (1, 15)]}, {'value2': [(2, 12), (1, 10)]}]

3 个答案:

答案 0 :(得分:0)

我建议这样做:

#First create a small dictionary, wich is used to get the keys(name,two,one):
smalld = {'name': 'value1', 'two': 25, 'one': 4}

#Then create the big dict, the dict you are going to get the data
bigd = [{'one': 4, 'name': 'value1', 'two': 25},
        {'one': 2, 'name': 'value1', 'two': 18},
        {'one': 1, 'name': 'value1', 'two': 15}, 
        {'one': 2, 'name': 'value2', 'two': 12}, 
        {'one': 1, 'name': 'value2', 'two': 10}]

#Then create empty final dict where you
#will use the other dict to create this one
finald = {}

#and now the "magic" loop. k get keys value and run over the big dict to get data.
for k in smalld.iterkeys():
    finald[k] = tuple(finald[k] for finald in bigd) #Edited, this line had a mistake

答案 1 :(得分:0)

试试这个:

>>> di = {}
>>> for i in a:
...   if di.get(i['name']):
...     di[i['name']].append((i['one'], i['two']))
...   else:
...     di[i['name']] = []
...     di[i['name']].append((i['one'], i['two']))

答案 2 :(得分:0)

a = [{'one': 4, 'name': 'value1', 'two': 25},
     {'one': 2, 'name': 'value1', 'two': 18},
     {'one': 1, 'name': 'value1', 'two': 15},
     {'one': 2, 'name': 'value2', 'two': 12},
     {'one': 1, 'name': 'value2', 'two': 10}]

_d = {ele['name']:[] for ele in a}

for _dict in a:
    _temp = {_dict['name']:(_dict['one'], _dict['two']) for ele in _dict}
    _d[_temp.keys()[0]].append(_temp[_temp.keys()[0]])
print _d

输出:

{'value2': [(2, 12), (1, 10)], 'value1': [(4, 25), (2, 18), (1, 15)]}