【问题标题】:How to insert a new key with a value in a specific position into a dictionary?如何将具有特定位置的值的新键插入字典中?
【发布时间】:2020-08-28 04:57:37
【问题描述】:

我有一个像这样的巨大字典列表,其中包含近 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 3.7 之前是无序的,并且在较新版本中按插入顺序排序,因此您可能必须根据您的版本使用OrderedDict,并且在任何一种情况下都需要重建字典。
  • @Rahul 我需要使用 xlsx 编写器将这些键的值打印到 excel 中。
  • 对于您明显的用例,named tuples 可能比字典更可取。

标签: python list dictionary ordereddict


【解决方案1】:

如果您的 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}]

对于 PythonOrderedDict:

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)

【讨论】:

    【解决方案2】:

    没有内置方法可以在 python dicts 中按某种顺序放置一些键。 您可以编写自己的函数,在插入后重新分配每个键,但 一般来说,依赖键顺序不是一个好主意。

    【讨论】:

      猜你喜欢
      • 2011-05-16
      • 2017-11-07
      • 2018-04-09
      • 2020-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-31
      相关资源
      最近更新 更多