【问题标题】:append key's value on same key在同一个键上附加键值
【发布时间】:2016-12-15 13:41:53
【问题描述】:

这是我目前拥有的

代码

coll = con['X']['Y']
s = "meta http equiv"

m = {'i': s}
n = json.dumps(m)
o = json.loads(n)
coll.insert(o)

数据

{ 
    "_id" : ObjectId("58527fe656c7a95cfaf40a15"), 
    "i" : "meta http equiv"
}

现在在下一次迭代中,s 将发生变化(根据我的计算),我想将 s 的值附加到同一个键

假设在下一次迭代中,s 在同一键 i 上变为 sample test data and

所以我想要这个

{ 
    "_id" : ObjectId("58527fe656c7a95cfaf40a15"), 
    "i" : "meta http equiv sample test data and"
}

如何做到这一点?

【问题讨论】:

    标签: python json mongodb


    【解决方案1】:

    改变你形成s的方式:

    s = "meta http equiv"
    s = (coll.get('i', '') + ' ' + s) if coll.get('i', '') else s
    

    如果 coll 不是 dict 对象,请改用 getattr

    s = "meta http equiv"
    s = (getattr(coll, 'i', '') + ' ' + s) if getattr(coll, 'i', '') else s
    

    【讨论】:

    • 对不起,哪个库有这个模块call
    • 我收到错误TypeError: 'Collection' object is not callable. If you meant to call the 'get' method on a 'Collection' object it is failing because no such method exists.
    • @Guru,coll 的类型是什么?您也可以尝试:将coll.get('i', '') 替换为getattr(coll, 'i', '')
    • coll 的类型为 <class 'pymongo.collection.Collection'>
    • 现在我收到TypeError: unsupported operand type(s) for +: 'Collection' and 'str'
    猜你喜欢
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 2022-11-11
    • 2021-05-09
    • 2023-01-09
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多