python - 更新 python 字典元素给出 [ ]

标签 python mongodb list python-2.7 dictionary

我的代码如下,我想更新列表中的一些项目:

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/

相关文章:

python - 如何获取类的所有实例

mongodb - 将外部数据导入 hdfs : is edge node a bottle neck?

python - 如何在pandas中创建半小时的桶

python - 在 python 中发送十六进制数据包

mongodb - 存储数百万个日志文件 - 每年大约 25 TB

java - 用于修改文档子文档属性键的聚合操作

java - 如果应用于有序项目列表,如何优化线性搜索?

python - 如何删除基于日期的重复元素

python - 在 pythonic 风格和列表理解方面遇到麻烦

Python raises exception 'generator' object does not support item assignment 而不是 'generator' object is not subscriptable