我的代码如下,我想更新列表中的一些项目:
coordinates = mongo_query.get_items({})
for json in coordinates:
json["person"] = "test"
json["location"] = "test"
for j in range(0, len(json["types"])):
json["types"][j] = "test"
new_coordinates = coordinates
当我调试变量 new_coordinates 时,它是空的,如下所示:'[]'
如果我执行 json_util.dumps(coordinates)
,坐标结果会给出:
coordinates= [{"name": "my name", "timestamp": {"$date": 1459002562091}, "longitude": 20.169550966746304, "location": "Work", "victim": {"language": "English", "locality": "Bern", "gender": "Other", "region": "Gabon", "birthday": {"$date": 506736000000}, "nationality": "United States", "ethnicity": "Bosnian"}, "person": "Stranger", "latitude": 43.05529651674635, "personGender": "Male", "types": ["Shouting"]}, {"name": "my name", "timestamp": {"$date": 1455632962091}, "longitude": 21.292620354706038, "location": "Public Space", "victim": {"language": "English", "locality": "Ferizaj", "gender": "Other", "region": "Kosovo", "birthday": {"$date": 601516800000}, "nationality": "Canada", "ethnicity": "Turkish"}, "person": "Waiter", "latitude": 42.81558228232729, "personGender": "Male", "types": ["Comments", "Whistling"]}]
为什么会发生这种情况我不明白为什么我无法更新坐标列表上的元素,以及为什么它给出一个空列表?有人可以帮助我吗?
编辑:
所以在这里可以更好地查看坐标:Jsonblob link
最佳答案
我重复了您的代码,导入 coordinates = <your .json file>
我能够修改坐标 - 请注意,您将“person”错误拼写为“peron”。
我会调查:
- 您确定您没有对坐标进行任何操作吗?
请注意
something = other_something
与说something = copy(other_something)
不同。 . - 是您在列表[坐标]中打印出来的坐标变量。
我建议您在 python shell 上重复我的过程:
coordinates = <copy the content that you've output through that link>
并在其中一个元素中尝试一下。这对我有用:coordinates = # copy the stuff here [ {} ] for json in coordinates: json['person'] = 'bla' new_coordinates = coordinates new_coordinates
输出:
[{'person': 'bla',...
关于python - 更新 python 字典元素给出 [ ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35892304/