简体   繁体   中英

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. I am using MongoDB as database.

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.

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. Do so with the $push operator. Note the second arg to update_one can have $push and $set and $unset operators.

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'}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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