python(prepend字典)

2024-04-19 02:38:45 发布

您现在位置:Python中文网/ 问答频道 /正文

使用python 3

所以我有两本字典

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

以及

^{pr2}$

为了将来的目的,我希望第二个字典中的最后一个对象是“new”对象

我想创建第三个(或新的)字典,最新条目(dict2的最后一个)位于

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

我可以在这里使用Surya的建议合并两个词典:Combine two dictionaries and remove duplicates in python

但这增加了我的新价值。有点像预科。在

如果我不清楚,请道歉。在

提前谢谢!在


Tags: 对象目的sourcenew字典anothercode条目
3条回答

请注意,lists在追加时非常有效,而在中则非常有效。但是,您可以这样做:

list.insert(0, element_to_insert)

你点的菜有单子。您可以通过分配给[0:0]片来为列表添加前缀:

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

您可以简单地连接列表中的元素:

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

相关问题 更多 >