【问题标题】:Add new key-value pair at the beginning of a dictionary在字典的开头添加新的键值对
【发布时间】:2020-06-11 08:05:48
【问题描述】:

我有字典列表。现在,在每个字典中,我想在字典的开头添加一个键值对(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}]

请提出解决方法

【问题讨论】:

    标签: python python-3.x dictionary key-value


    【解决方案1】:

    在python3.7+(cpython3.6+)上,字典是有序的,所以你可以创建一个新的字典,以“message”作为第一个键:

    for i, d in enumerate(data):
        data[i] = {'message': '111', **d}
    

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

    【讨论】:

    • 我尝试了上面的 sn-p....我收到错误,因为“列表索引必须是整数或切片,而不是 dict”i.imgur.com/8PGUqr1.png
    • @Mahesh 哎呀,刚刚修复了代码中的一个错误,PTAL
    【解决方案2】:

    简单的方法是先创建一个字典:

    data = {'m1': 'A', 'm2': 'D'}
    

    然后使用更新:

    data.update({'m3': 'C', 'm4': 'B'})
    

    结果将是{'m1': 'A', 'm2': 'D', 'm3': 'C', 'm4': 'B'}。对于有序字典,假设是 python 版本 3.7+。其他方式可以使用collections.OrderedDict

    【讨论】:

      猜你喜欢
      • 2020-08-11
      • 2018-05-27
      • 1970-01-01
      • 2020-08-17
      • 2015-09-07
      • 2016-10-29
      • 1970-01-01
      • 1970-01-01
      • 2019-11-07
      相关资源
      最近更新 更多