如何将具有特定位置值的新键插入字典中?

How to insert a new key with a value in a specific position into a dictionary?

我有一个庞大的字典列表,其中有将近 100 个条目。

[{ "color":-65536, 
  "touch_size":0.21960786,
  "touch_x":831.25,
  "touch_y":1597.2656
},
{ "color":-65536,
  "touch_size":0.20392159,
  "touch_x":1302.5,
  "touch_y":1496.0938
}, .... {}]

我想在每个字典的特定位置插入 2 个带有值的新键。

new_keys = ['touch_x_dp','touch_y_dp']

touch_x_dp需要放在键touch_x之后,touch_y_dp需要放在touch_y之后 这些值需要用 None 初始化。

我试过了,但这并没有把它们放在我需要的地方。

for key in dp_keys:data['attempts'][i]["items"][j][key]=None

没有构建方法可以在 python 字典中按某种顺序放置一些键。 您可以编写自己的函数,在插入后退出每个键,但是 一般来说,依靠按键命令不是一个好主意。

如果您的 Python 是 3.7+,您可以执行以下操作:

data = [{"color": -65536,
         "touch_size": 0.21960786,
         "touch_x": 831.25,
         "touch_y": 1597.2656
         },
        {"color": -65536,
         "touch_size": 0.20392159,
         "touch_x": 1302.5,
         "touch_y": 1496.0938
         }]

fields_order = ["color", "touch_size", "touch_x", "touch_x_dp", "touch_y", "touch_y_dp"]
payload = []
for d in data:
    entity = dict([(f, d.get(f)) for f in fields_order])
    payload.append(entity)

print(payload)
# output: [{'color': -65536, 'touch_size': 0.21960786, 'touch_x': 831.25, 'touch_x_dp': None, 'touch_y': 1597.2656, 'touch_y_dp': None}, {'color': -65536, 'touch_size': 0.20392159, 'touch_x': 1302.5, 'touch_x_dp': None, 'touch_y': 1496.0938, 'touch_y_dp': None}]

对于Python<3.7,你应该使用OrderedDict:

from collections import OrderedDict

fields_order = ["color", "touch_size", "touch_x", "touch_x_dp", "touch_y", "touch_y_dp"]
payload = []
for d in data:
    entity = OrderedDict([(f, d.get(f)) for f in fields_order])
    payload.append(entity)

print(payload)