Marty Wallace
Marty Wallace

Reputation: 35734

Appending/Merging in Python

I have the following structure:

[
  {
    u'123456': {'name': "Bill"}, 
    u'234567': {'name': "Dave"},
    u'345678': {'name': "Tom"}
  },
]

During a for loop new items are added to the list using the extend function. Unfortunately this results in the following structure:

    [
      {
        u'123456': {'name': "Bill"}, 
        u'234567': {'name': "Dave"},
        u'345678': {'name': "Tom"}
      },
      {
        u'555555': {'name': "Steve"}, 
        u'666666': {'name': "Michael"},
        u'777777': {'name': "George"}
      }
    ]

The intended result is actually a flat structure such in the following:

    [
      {
        u'123456': {'name': "Bill"}, 
        u'234567': {'name': "Dave"},
        u'345678': {'name': "Tom"},
        u'555555': {'name': "Steve"}, 
        u'666666': {'name': "Michael"},
        u'777777': {'name': "George"}
      }
    ]

Is it possible to append to the list so that the structure gets built in a flat way.

or

Is it possible to flatten after the loop has finished?

Upvotes: 1

Views: 60

Answers (4)

Mariusz Jamro
Mariusz Jamro

Reputation: 31643

You can use .update(), however this will overwrite values if you'll have duplicated keys.

def flatten(results):
    newresult = {}
    for subdict : results:
        newresult.update(subdict)
    return [newresult]

Upvotes: 0

TerryA
TerryA

Reputation: 59974

You can add the items of both dictionaries together:

>>> mylist = [
  {
    u'123456': {'name': "Bill"}, 
    u'234567': {'name': "Dave"},
    u'345678': {'name': "Tom"}
  },
]
>>> mydict = {
  u'555555': {'name': "Steve"}, 
  u'666666': {'name': "Michael"},
  u'777777': {'name': "George"}
}
>>> [dict(mylist[0].items() + mydict.items())]
[{u'123456': {'name': 'Bill'}, u'555555': {'name': 'Steve'}, u'777777': {'name': 'George'}, u'666666': {'name': 'Michael'}, u'345678': {'name': 'Tom'}, u'234567': {'name': 'Dave'}}]

Although it's more clean to just do .update():

>>> mylist[0].update(mydict)

Upvotes: 0

RichieHindle
RichieHindle

Reputation: 281475

Where you currently have something like this:

mylist.extend(newdict)

You should use this:

mylist[0].update(newdict)

Upvotes: 1

TobiMarg
TobiMarg

Reputation: 3797

If your list is named l you could use l[0].update(new_dict). Example:

l = [{u'123456': {'name': "Bill"}}]
l[0].update({u'234567': {'name': "Dave"}})
print(l)

Nice formatted output is:

[
    {
       u'123456': {'name': 'Bill'}, 
       u'234567': {'name': 'Dave'}
    }
]

Upvotes: 2

Related Questions