简体   繁体   English

包含包含更多词典的列表的词典-更新

[英]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. 只是标有“ Items”的键及其下的列表,其中包含更多词典。

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. 您的示例似乎很正常,因为如果字典中存在给定的键,则字典update()方法将覆盖值。

my_dict2 has key 'result' which has a value {'items': [{'Test3': 1000},{'Test4': 2000}]} . my_dict2具有键'result' ,其值为{'items': [{'Test3': 1000},{'Test4': 2000}]}

You're overriding the value of 'result' with my_dict_values which is {'items': [{'Test': 1000}, {'Test2': 2000}]} 您正在使用my_dict_values覆盖'result'的值,该值是{'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 您正在使用update覆盖“结果”值,可能会更改该行

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

to

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

will do it for you 会为你做

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

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