-3

Could somebody help me to transform this:

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}]

to something like this:

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

3 回答 3

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']))
于 2013-11-09T09:27:50.217 回答
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
于 2013-11-09T08:35:15.383 回答
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)]}
于 2013-11-09T09:32:28.117 回答