【发布时间】:2017-10-25 17:04:12
【问题描述】:
我在向 JSON 字典添加新元素时遇到问题。 该问题似乎与不允许重复键的 python 字典有关。我该如何处理这个限制?
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'}
我的代码导致无效的字典/json。
【问题讨论】:
-
JSON 也不允许重复键。
-
current_dict有一个引用列表的entries键。你的意思是追加到那个列表吗? -
@MartijnPieters:没错!我该怎么做?
-
请注意,您没有重复的密钥。你有一本字典,其中一个值是字典的list。这些都不是 JSON 特定的,你有 Python 数据结构。结构是从 JSON 加载的,这点现在既不存在也不存在。
-
@user1155413:与附加到任何其他列表的方式相同。使用
list.append()方法。current_dict['entries']是列表对象,因此current_dict['entries'].append(new_data)将附加到该列表中。
标签: python json dictionary