-4

I'm trying to merge two lists that I have.

gpbdict = dict(zip(namesb, GPB))
>>> {'1': True, '3': True, '2': True, '5': True, '4': True, '7': True, '6': True, '8': True}
gpadict = dict(zip(namesa, GPA))
>>> {'11': True, '10': True, '13': True, '12': True, '15': True, '14': True, '16': True, '9': True}

However, it doesn't seem to be as simple as just:

 json.loads(gpadict + gpbdict)

or

gpa_gpb = [gpadict, gpbdict]
print json.dumps(gpa_gpb, indent=2, sort_keys=True))

Only the later will produce a result with two separate lists:

>>>[
>>>  {
>>>    "10": true,
>>>    "11": true,
>>>    "12": true,
>>>    "13": true,
>>>    "14": true,
>>>    "15": true,
>>>    "16": true,
>>>    "9": true
>>>  },
>>>  {
>>>    "1": true,
>>>    "2": true,
>>>    "3": true,
>>>    "4": true,
>>>    "5": true,
>>>    "6": true,
>>>    "7": true,
>>>    "8": true
>>>  }
>>>]

Is there a step I'm missing?

Anand Tripathi
  • 14,556
  • 1
  • 47
  • 52
user5740843
  • 1,540
  • 5
  • 22
  • 42
  • 2
    Possible duplicate of [How to merge two Python dictionaries in a single expression?](http://stackoverflow.com/questions/38987/how-to-merge-two-python-dictionaries-in-a-single-expression) – mkrieger1 Mar 03 '17 at 10:50
  • You can easy find answer to this question thru google. Veeeeery easy. Also you should learn more about Python terms. – Greg Eremeev Mar 03 '17 at 10:53
  • @anandtripathi Caution! `update` method on dictionaries does *not* return anything. But the essence of your comment is true and valid. – MariusSiuram Mar 03 '17 at 10:56
  • This has nothing to do with JSON or lists. – Stefan Pochmann Mar 03 '17 at 11:02
  • I realised that and we cannot edit the comment so i had to delete that @MariusSiuram sorry for the inconvenience – Anand Tripathi Mar 03 '17 at 11:21

1 Answers1

3

You are doing some strange stuff.

First of all, you want to merge Python objects, don't you? And why and how? Both gpbdict and gpbadict are dictionaries (not list) so your question is not very specific. And json.loads is expected to receive a string (a JSON) not a Python object. So, maybe you simply want:

gpbadict = dict(zip(namesb + namesa, GPB + GPA))

Note that the operator + works ok with lists, but not with dictionaries.

If you want to merge dictionaries, on the other hand, you could use the update:

gpadict.update(gpbdict)

And that will effectively merge the dictionary: gpadict will become the combination of both gpadict (the starting one) and gpbdict. If there are repeteated keys, they will be overwritten.

And in the whole question I could not find any real reference to JSON. I am missing something?

MariusSiuram
  • 3,380
  • 1
  • 21
  • 40