2016-08-01 36 views
0
list_1 = [{'1': 'name_1', '2': 'name_2', '3': 'name_3',}, 
     {'1': 'age_1', '2': 'age_2' ,'3': 'age_3',}] 

我想操作這個列表,使得字典包含特定ID的所有屬性。身份證本身必須構成結果字典的一部分。輸出示例如下所示:重建Python中的字典列表,但結果不是按順序的

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

然後我做了以下內容:

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

然後給出:

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

但我不明白爲什麼 'ID' 是表示第二個位置,而'年齡'顯示第一?

我試過其他方法,但結果是一樣的。任何人都可以幫助解決它?

+0

我認爲這是相當重複cate:http://stackoverflow.com/q/1867861/42346 – bernie

+1

python詞典沒有順序。你必須訂購字典 –

回答

1

爲了保持秩序,你應該使用一個ordered dictionary 。使用您的樣本:

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

打印順序列表...

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

NAME_1 age_1

NAME_3 age_3

NAME_2 age_2

0

嘗試使用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()] 

這更可能是保持你想要的順序。我對Python仍然很陌生,所以這可能不是超級Pythonic,但我認爲它會起作用。

輸出 -

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

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

例子: https://pymotw.com/2/collections/ordereddict.html

獲取構造權: Right way to initialize an OrderedDict using its constructor such that it retains order of initial data?