How to Add Key-Value to Dictionary During List Comprehension in Python


I had an object that followed this structure.

data = {
  'id': 0,
  'source': {
    'key1': 'value1',
    'key2': 'value2'
  }
}

I needed a quick way to convert this object to the following:

data = {
  'id': 0,
  'key1': 'value1',
  'key2': 'value2'
}

Double Asterisks

We can use ** to dump the key-value pairs from a dictionary into another dictionary.

It’s known as “dictionary unpacking” in Python.

We can then construct a new dictionary using dict().

newdata = [dict(d['source'], **{'id': d['id']}) for d in data]