简体   繁体   English

在python字典中添加新的键值对

[英]Add new key-value pair in python dict

I am facing problem while trying to add a new key-value pair in python dictionary while keeping previous key-value pairs. 我在尝试在python字典中添加新的键值对同时保留以前的键值对时遇到问题。 I am using MongoDB as database. 我正在使用MongoDB作为数据库。

My Sample response is 我的样本回复是

"field1" : "a",
"field2" : "b",
"field3" : "c",
"history" : {
    "2019-09-03 00:00:00" : "state1"
}

Expected response is 预期的响应是

"field1" : "a",
"field2" : "b",
"field3" : "c",
"history" : {
    "2019-09-01 00:00:00" : "state1"
    "2019-09-02 00:00:00" : "state1"
    "2019-09-03 00:00:00" : "state1"
}

I want to add key-value pair in history, the key is date and value will be state but the problem is my code removes the previous key-value pairs and then add a new key-value pair. 我想在历史记录中添加键值对,键是日期,值将是状态,但是问题是我的代码删除了先前的键值对,然后添加了新的键值对。

I am using mongo client to save a record in MongoDB data. 我正在使用mongo client将记录保存在MongoDB数据中。

here is my code 这是我的代码

out = dict()
history = dict()
out['field1'] = 'a'
out['filed2'] = 'b'
out['field3'] = 'c'
history[str(datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0))] = 'state1'
out_handle.update_one(
                    {'field1': a, 'field2': 'b', 'field3': 'c'},
                    {'$set': out}},
                    upsert=True
                )

It looks like you wish to query by the three fields {'field1': a, 'field2': 'b', 'field3': 'c'} and then just add a history record. 好像您希望通过三个字段{'field1': a, 'field2': 'b', 'field3': 'c'} ,然后仅添加历史记录。 Do so with the $push operator. 使用$push运算符执行此操作。 Note the second arg to update_one can have $push and $set and $unset operators. 请注意, update_one的第二个arg可以具有$push$set$unset运算符。

coll.update_one({'field1': a, 'field2': 'b', 'field3': 'c'}, {
        "$push": {"history":{"D2":"S3"}},
        "$set": {"otherField1": "hello", "otherField2": "goodbye"}
        }, upsert=True)

BUT I highly recommend you do not use dates as keys but rather as value, and as real datetime values, not strings. 但是,我强烈建议您不要将日期用作键,而应将其用作值,以及作为实际日期时间值而不是字符串。 It is much easier to deal with date queries when they are a value an not a key, eg 当日期查询是值而不是键时,处理日期查询要容易得多,例如

rec = {
    "date": datetime.datetime.now(),
    "state": "state1"  # or whatever
}
coll.update_one({'field1': a, 'field2': 'b', 'field3': 'c'}, {"$push": {"history":rec}} )

This yields something like: 这将产生如下内容:

{
    "field1" : "a",
    "field2" : "b",
    "field3" : "c",
    "history" : [
        {
            "date" : ISODate("2019-09-03T07:54:38.144Z"),
            "state" : "state1"
        },
        {
            "date" : ISODate("2019-09-03T07:54:38.144Z"),
            "state" : "state2"
        }
    ]
}

This can be solution: 这可以解决:

create sub-dictionary to insert inside parent dictionary: 创建子词典以插入父词典中:

    history[str(datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0, day=1))] = 'state1'
    history[str(datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0, day=2))] = 'state1'
    history[str(datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0, day=3))] = 'state1'

insert sub dictionary inside parent 'out' dictionaty 在父“出”字典中插入子字典

    out['history']=history

effect 影响

    {'field1': 'a',
    'filed2': 'b',
    'field3': 'c',
    'history': {'2019-09-03 00:00:00': 'state1',
    '2019-09-02 00:00:00': 'state1',
    '2019-09-01 00:00:00': 'state1'}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM