0
list_1 = [{'1': 'name_1', '2': 'name_2', '3': 'name_3',}, 
       {'1': 'age_1', '2': 'age_2' ,'3': 'age_3',}]

I want to manipulate this list so that the dicts contain all the attributes for a particular ID. The ID itself must form part of the resulting dict. An example output is shown below:

list_2 = [{'id' : '1', 'name' : 'name_1', 'age': 'age_1'},
       {'id' : '2', 'name' : 'name_2', 'age': 'age_2'},
       {'id' : '3', 'name' : 'name_3', 'age': 'age_3'}]

Then I did following:

>>> list_2=[{'id':x,'name':list_1[0][x],'age':list_1[1][x]} for x in list_1[0].keys()]

Then it gives:

>>> list_2
    [{'age': 'age_1', 'id': '1', 'name': 'name_1'}, 
     {'age': 'age_3', 'id': '3', 'name': 'name_3'}, 
     {'age': 'age_2', 'id': '2', 'name': 'name_2'}]

But I don't understand why 'id' is showing in the second position while 'age' showing first?

I tried other ways but the result is the same. Any one can help to figure it out?

mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
Aaron
  • 35
  • 5

2 Answers2

1

To keep the order, you should use an ordered dictionary. Using your sample:

new_list = [OrderedDict([('id', x), ('name', list_1[0][x]), ('age', list_1[1][x])]) for x in list_1[0].keys()]

Printing the ordered list...

for d in new_list:                                                                                            
    print(d[name], d[age])

name_1 age_1

name_3 age_3

name_2 age_2

Jose Raul Barreras
  • 849
  • 1
  • 13
  • 19
0

Try using an OrderedDict:

list_1 = [collections.OrderedDict([('1','name_1'), ('2', 'name_2'), ('3', 'name_3')]),
        collections.OrderedDict([('1','age_1'),('2','age_2'),('3', 'age_3')])]

list_2=[collections.OrderedDict([('id',x), ('name',list_1[0][x]), ('age', list_1[1][x])]) 
        for x in list_1[0].keys()]

This is more likely to preserve the order you want. I am still new to Python, so this may not be super Pythonic, but I think it will work.

output -

In [24]: list( list_2[0].keys() )
Out[24]: ['id', 'name', 'age']

Docs: https://docs.python.org/3/library/collections.html#collections.OrderedDict

Examples: https://pymotw.com/2/collections/ordereddict.html

Getting the constructors right: Right way to initialize an OrderedDict using its constructor such that it retains order of initial data?

Community
  • 1
  • 1
David
  • 1,224
  • 10
  • 20