Search code examples
pythonlistdictionaryordereddict

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


I have a huge List of dictionary like this which has almost 100 entries.

[{ "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
}, .... {}]

I want to insert 2 new keys with values in each dictionary on a particular position.

new_keys = ['touch_x_dp','touch_y_dp']

touch_x_dp needs to be placed after key touch_x and touch_y_dp needs to be placed after touch_y The values for these need to be initialized with None.

I have tried this but this does not place them where I need.

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

Solution

  • If your Python is 3.7+, you can do the following:

    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}]
    
    

    For Python<3.7, you should use 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)