Merge two lists and create a new dictionary
<p>I could not find a good way to do this. Suppose I have two lists (the lists have objects with given attributes). I need to create a new dictionary/list with merged atttributes.</p>

<pre><code>listA = [
  {
    "alpha": "some value",
    "time": "datetime",
  },
  ...
]

listB = [
  {
    "beta": "some val",
    "gamma": "some val",
    "time": "datetime"
  },
  ...
]
</code></pre>

<p>The result should be as follows (it should be merged based on "time" attribute)</p>

<pre><code>result = {
  "datetime": {
    "alpha": "some value",
    "beta": "some val",
    "gamma": "some val"
  },
  ...
}
</code></pre>

<p>How do I do this in a python way?</p>

<p>For example,</p>

<pre><code>listA = [
  {
    "time": "Jan 1",
    "alpha": "one"
  },
  {
    "time": "Jan 3",
    "alpha": "three"
  }
]

listB = [
  {
    "beta": "one-one",
    "gamma": "one-two",
    "time": "Jan 1"
  },
  {
    "beta": "two-one",
    "gamma": "two-two",
    "time": "Jan 2"
  },
]

result = {
  "Jan 1": {
    "alpha": "one",
    "beta": "one-one",
    "gamma": "one-two",
  },
  "Jan 2": {
    "beta": "two-one",
    "gamma": "two-two",
  },
  "Jan 3": {
    "alpha": "three"
  }
}
</code></pre>

<p>This code might be a good start:</p>

<pre><code>listA = [
  {
    "time": "Jan 1",
    "alpha": "one"
  },
  {
    "time": "Jan 3",
    "alpha": "three"
  }
]

listB = [
  {
    "beta": "one-one",
    "gamma": "one-two",
    "time": "Jan 1"
  },
  {
    "beta": "two-one",
    "gamma": "two-two",
    "time": "Jan 2"
  },
]
result = {}

# We consider every element of A and B one by one
for elem in listA + listB:
    key = elem["time"]

    # If that is the first time we encounter that key, we create a new empty dict in result
    if not result.get(key, None):
        result[key] = {}

    # We copy the content of the elem in listA or listB into the right dictionnary in result.
    for dictKey in elem.keys():

        # We don't want to copy the time
        if dictKey == "time":
            continue
        result[key][dictKey] = elem[dictKey]
print(result)
</code></pre>

python list dictionary