2016-12-25 11 views
0

使ってPython 3先頭に追加辞書(パイソン)

は、だから私は2つの辞書

すなわち

[{'code': '123456', 'reward': 'awesome reward', 'source': 'awesome source'}, 
{'code': '12345', 'reward': 'some reward', 'source': 'some source'} 
] 

と将来の目的のために

[ {'code': '123456', 'reward': 'awesome reward', 'source': 'awesome source'} 
    {'code': '12345', 'reward': 'some reward', 'source': 'some source'}, 
    {'code': '54321', 'reward': 'another reward', 'source': 'another source'} 
] 

を持っている私はで最後のオブジェクトをしたいです2番目の辞書は「新しい」オブジェクトです

は、私はここにスーリヤの提案を使用して2つの辞書をマージすることができています

[ {'code': '54321', 'reward': 'another reward', 'source': 'another source'}, 
    {'code': '123456', 'reward': 'awesome reward', 'source': 'awesome source'} 
    {'code': '12345', 'reward': 'some reward', 'source': 'some source'} 
] 

ことを一番上に最新のエントリ(辞書2の最後の1)と第三(または新規)辞書を作成したい:Combine two dictionaries and remove duplicates in python

これは私の新しい価値を追加します。私はいくつかの並べ替え機能を探しています。

私は明確でない場合は謝罪します。

ありがとうございます!

+4

あなたは2本の*リスト*持っている、*辞書を含む各*。 –

答えて

2

ご注文はリストに記載されています。あなたは[0:0]スライスに割り当てることによって、リストの前に追加することができます

a = [1, 2, 3] 
a[0:0] = [4] 
# a is now [4, 1, 2, 3] 
1

注意をlist sが追加で非常に効率的であり、先頭追加で効率的で非常にこと。ただし、このように前に付加することができます

list.insert(0, element_to_insert) 
+0

ありがとう、これは私のために働いた! (私はまだupvoteできません) 誰もが私を助けてくれてありがとう! – Chrizlee

1

あなたは、単にリストの要素を連結できます。

[x for x in d2 if x not in d1] + [x for x in d2 if x in d1]