-2

I have the following list of dicts in python.

[
{
"US": {
"Intial0": 12.515
},
{
"GE": {
"Intial0": 11.861
}
},
{
"US": {
"Final0": 81.159
}
},
{
"GE": {
"Final0": 12.9835
}
}
]

I want the final list of dicts as

[{"US": {"Initial0":12.515, "Final0": 81.159}}, {"GE": {"Initial0": 11.861, "Final0": 12.9835}}]

I am struggling with this from quite some time . Any help?

station
  • 6,715
  • 14
  • 55
  • 89
  • Why do you want that, instead of a single dict of dicts? `{"US": {...}, "GE": {...}}`? – Daniel Roseman Jan 05 '16 at 13:19
  • Related [How to merge multiple dicts with same key?](http://stackoverflow.com/questions/5946236/how-to-merge-multiple-dicts-with-same-key) – fredtantini Jan 05 '16 at 13:20
  • 2
    Rohit, what have you tried? Have you looked at using update? http://www.tutorialspoint.com/python/dictionary_update.htm – cicit Jan 05 '16 at 13:23
  • fredtantini, check out these previous posts. Here are 2 of them: http://stackoverflow.com/questions/5946236/how-to-merge-multiple-dicts-with-same-key and http://stackoverflow.com/questions/6813564/python-have-dictionary-with-same-name-keys. – cicit Jan 05 '16 at 13:28

2 Answers2

1

You could use Python's defaultdict as follows:

from collections import defaultdict

lod = [
    {"US": {"Intial0": 12.515}},
    {"GE": {"Intial0": 11.861}},
    {"US": {"Final0": 81.159}},
    {"GE": {"Final0": 12.9835}}]

output = defaultdict(dict)

for d in lod:
    output[d.keys()[0]].update(d.values()[0])

print output

For the data given, this would display the following:

defaultdict(<type 'dict'>, {'GE': {'Intial0': 11.861, 'Final0': 12.9835}, 'US': {'Intial0': 12.515, 'Final0': 81.159}})

Or you could convert it back to a standard Python dictionary with print dict(output) giving:

{'GE': {'Intial0': 11.861, 'Final0': 12.9835}, 'US': {'Intial0': 12.515, 'Final0': 81.159}}
Martin Evans
  • 45,791
  • 17
  • 81
  • 97
0

list1=[{"US": {"Intial0": 12.515}},{"GE": {"Intial0": 11.861}},{"US": {"Final0": 81.159}},{"GE": {"Final0": 12.9835}}]

dict_US={} dict_GE={} for dict_x in list1: if dict_x.keys()==['US']: dict_US.update(dict_x["US"]) if dict_x.keys()==['GE']: dict_GE.update(dict_x["GE"]) list2=[{"US":dict_US},{"GE":dict_GE}] print list2

Aaron
  • 35
  • 5