简体   繁体   中英

Dict containing a list containing more dicts - Updating

Below I have a simple program. What i intend to do is to merge the two dictionaries. But i don't want to copy any of the values in regards to offset, limit, results. Just the key labeled "Items" and the list under that, containing more dictionaries.

My problem is is that i can pull the list under, items and store it in a variable which removes the other keys, however when i go to add it to the other list, instead of updating, it replaces the values.

For instance i have two dictionaries:

my_dict: {'status': 'ok', 'result': {'items': [{'Test': 1000}, {'Test2': 2000}]}}
my_dict2: {'status': 'ok', 'result': {'items': [{'Test3': 1000}, {'Test4': 2000}]}} 

My result i expect is:

my_dict2: {'status': 'ok', 'result': {'items': [{'Test3': 1000}, {'Test4': 2000}, {'Test': 1000}, {'Test2': 2000}]}}

But i get:

my_dict2: {'status': 'ok', 'result': {'items': [{'Test': 1000}, {'Test2': 2000}]}}

code:

my_dict = {
    "status": "ok",
    "result": {
        "offset": 0,
        "limit": 1000,
        "total": 839,
        "items": [
            {
}
]
}
}

my_dict2 = my_dict

my_dict.update({'result': {'items': [{'Test': 1000},{'Test2': 2000}]}})
my_dict_values = my_dict['result']['items']

my_dict2.update({'result': {'items': [{'Test3': 1000},{'Test4': 2000}]}})
print "Before: %s" % (my_dict2)
my_dict2.update({'result': {'items': my_dict_values}})
print "After: %s" % (my_dict2)

Your example seems normal because dictionary update() method overrides values if given key exists in the dictionary.

my_dict2 has key 'result' which has a value {'items': [{'Test3': 1000},{'Test4': 2000}]} .

You're overriding the value of 'result' with my_dict_values which is {'items': [{'Test': 1000}, {'Test2': 2000}]}

To get expected results, you might wanna try:

my_dict2['result']['items'].extend(my_dict_values)

You are overriding the 'result' value by using update, maybe changing the line

my_dict2.update({'result': {'items': my_dict_values}})

to

my_dict2['results']['items'] += my_dict_values

will do it for you

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