【问题标题】:How do I extract keys from a dictionary that has {"key":[{"A":"1"},{"B":"2"}]?如何从具有 {"key":[{"A":"1"},{"B":"2"}] 的字典中提取键?
【发布时间】:2019-08-20 18:47:06
【问题描述】:

我有一本 python 字典,

dict = {
    "A": [{
        "264": "0.1965"
    }, {
        "289": "0.1509"
    }, {
        "192": "0.1244"
    }]
}

我在 mongoDB 中有一个集合,

{
    "_id": ObjectId("5d5a7f474c55b68a873f9602"),
    "A": [{
            "264": "0.5700"
        }, {
            "175": "0.321"
        }
    }

    {
        "_id": ObjectId("5d5a7f474c55b68a873f9610"),
        "B": [{
                "152": "0.2826"
            }, {
                "012": "0.1234"
            }
        }
}

我想看看 dict 中的键“A”是否在 mongodb 中可用。如果是,我想遍历列表中的键,即

[{
    "264": "0.19652049960139123"
}, {
    "289": "0.1509138215380371"
}, {
    "192": "0.12447470015715734"
}]
}

并检查 264 是否在 mongodb 中可用并更新键值 else append。

mongodb 中的预期输出:

{
"_id": ObjectId("5d5a7f474c55b68a873f9602"),
"A": [{
        "264": "0.1965"
    }, {
        "175": "0.321"
    }, {
        "289": "0.1509"
    }, {
        "192": "0.1244"
    }
}

{
    "_id": ObjectId("5d5a7f474c55b68a873f9610"),
    "B": [{
            "152": "0.2826"
        },{
            "012": "0.1234"
     }
    }

密钥 264 的值已更新。请帮忙。

【问题讨论】:

  • 为什么从 mongodb 中删除键“B”中的 {"012" : "0.1234"}?

标签: python mongodb pymongo


【解决方案1】:

假设您正在寻找 python 部分而不是 mongoDB,请尝试:

for k,v in dict['A'].items(): #k is key, v is value
   process_entry(k, v) #do what you want with the database

【讨论】:

  • 我想使用 pymongo 在 mongodb 中更新它。
【解决方案2】:

假设您的 mongodb 集合称为 your_collection

   data= your_collection.find_one({'A':{'$exists':1}})

   if data:
       #loop over the keys
       for item in data['A']:
           #check whether a certain key is available
           if 'some_key' not in item:
               do_something()# update 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 2019-01-22
    相关资源
    最近更新 更多