-3

I'm having trouble adding a new element to a JSON Dictionary. The issue seems to be related to python dictionaries not allowing duplicate keys. How can I deal with this restriction?

import json
import datetime

current_dict = json.loads(open('cad_data.json').read())

print(current_dict)
# {'entries': [{'cad_value': '518', 'timestamp': '2017-10-24 16:15:34.813480'}, {'cad_value': '518', 'timestamp': '2017-10-24 17:15:34.813480'}]}

new_data = {'timestamp': datetime.datetime.now(), 'cad_value': '518'}

current_dict.update(new_data)
print(current_dict)
# {'entries': [{'cad_value': '518', 'timestamp': '2017-10-24 16:15:34.813480'}, {'cad_value': '518', 'timestamp': '2017-10-24 17:15:34.813480'}], 'timestamp': datetime.datetime(2017, 10, 25, 13, 44, 20, 548904), 'cad_value': '518'}

My code leads to an invalid dictionary/json.

user1155413
  • 169
  • 3
  • 11
  • 1
    JSON doesn't allow duplicate keys either. – user2357112 Oct 25 '17 at 17:05
  • 1
    `current_dict` has an `entries` key that references a list. DId you mean to *append to that list* perhaps? – Martijn Pieters Oct 25 '17 at 17:06
  • @MartijnPieters: that's correct! how would i do that? – user1155413 Oct 25 '17 at 17:07
  • Note that you don't have duplicate keys. You have a dictionary, where the one value is a *list* of dictionaries. None of this is JSON specific, you have Python data structures. That the structure was loaded from JSON is neither here nor there at this point. – Martijn Pieters Oct 25 '17 at 17:07
  • @user1155413: the same way you'd append to any other list. With the `list.append()` method. `current_dict['entries']` is the list object, so `current_dict['entries'].append(new_data)` would append to that list. – Martijn Pieters Oct 25 '17 at 17:08
  • @user2357112 that's not enterily correct. please check https://stackoverflow.com/questions/21832701/does-json-syntax-allow-duplicate-keys-in-an-object – user1155413 Oct 25 '17 at 17:08
  • @MartijnPieters thank you!!! that worked perfectly! please add it as an answer so I can mark it as correct – user1155413 Oct 25 '17 at 17:11

1 Answers1

1

You updated the outermost dictionary. You don't want to update any dictionary, you want to add another dictionary to the entries list:

current_dict['entries'].append(new_data)

Here current_dict['entries'] is an expression that resolves to the list object with dictionaries, and the above calls list.append() on that list object to add the new_data reference to the list, effectively adding another dictionary.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • thank you very much Martijin for your help and for clearly explaining what I was doing wrong. I really appreciate your help! – user1155413 Oct 25 '17 at 17:20