在字典的开头添加键值对|| Python

问题描述 投票:0回答:1

我有字典清单。现在,在每本字典中,我想在dict的开头添加一个键值对(key:'message1'),但是当我添加它时,其添加到末尾。] >

以下是我的代码

data=[{
'message2': 'asd',
'message3': 'fgw',
'message4': 'fgeq',
'message5': 'gqe',
'message6': 'afgq',
'message7': 'major',
'message8': 'color-regular'
}]
for i in data:
    i['message1'] = '111'

以下是我得到的输出,其中message1 末尾追加

[{'message2': 'asd',
'message3': 'fgw',
  'message4': 'fgeq',
  'message5': 'gqe',
  'message6': 'afgq',
  'message7': 'major',
  'message8': 'color-regular',
  'message1': '111'# i want this in the beginning}]

请提出解决方法

我有字典清单。现在,在每本字典中,我都想在字典的开头添加一个键值对(key:'message1'),但是当我添加它时,它的末尾将被添加。以下是我的...

python-3.x dictionary key-value
1个回答
0
投票

在python3.7 +(cpython3.6 +)上,字典是有序的,因此您可以使用“消息”作为第一个键来创建新字典:

© www.soinside.com 2019 - 2024. All rights reserved.