最佳实践是更新包含列表和字典的字典列表中的字段。

huangapple go评论66阅读模式
英文:

best practice to update a field in list of dictionary of list and dictionary

问题

你想要更新这个部分,将"aaaa"和"bbb"添加进去:

"instance[]": [
    {
        "key": "requires",
        "value": {
            "string[]": ["aaaa", "bbb"]
        }

你可以使用以下方法来更新它:

# 找到包含"key"为"order"的字典
newl = [d for d in test if d["key"] == "order"]

# 检查是否找到了匹配的字典
if newl:
    # 在匹配的字典中找到"instance[]"部分
    instance_list = newl[0]["value"]["instance[]"]
    
    # 在"requires"字典中添加"aaaa"和"bbb"
    for instance in instance_list:
        if instance["key"] == "order_det":
            instance["value"]["instance[]"][0]["value"]["string[]"].extend(["aaaa", "bbb"])

# 打印更新后的test列表
print(test)

这将会更新你的test列表,添加"aaaa"和"bbb"到指定的位置。

英文:

Assuming the input is a list of dictionary.
I need to update a specific field with new values.
There are repeated keys, values in the input so cannot distinguish the field need to be picked by its name.
Here is an example:

test = [
{
    "key": "prog",
    "value": {
        "instance[]": [
            {
                "key": "name",
                "value": {
                    "string": "NAME"
                },
                "verif": 22222222
            },
            {
                "key": "user",
                "value": {
                    "string": "AAAAA"
                },
                "verif": 22222222
            }
        ]
    },
    "verif": 22222222
},
{
    "key": "sytem_platform",
    "value": {
        "bool": "false"
    },
    "verif": 22222222
},
{
    "key": "system_beh",
    "value": {
        "bool": "true"
    },
    "verif": 22222222
},
{
    "key": "check_beh",
    "value": {
        "bool": "true"
    },
    "verif": 22222222
},
{
    "key": "order",
    "value": {
        "instance[]": [
            {
                "key": "order_det",
                "value": {
                    "instance[]": [
                        {
                            "key": "requires",
                            "value": {
                                "string[]": []
                            },
                            "verif": 22222222
                        },
                        {
                            "key": "status",
                            "value": {
                                "string[]": []
                            },
                            "verif": 22222222
                        },
                        {
                            "key": "system_status",
                            "value": {
                                "string[]": [
                                    "sys1.out",
                                    "sys1.checking"
                                ]
                            },
                            "verif": 22222222
                        },
                        {
                            "key": "weather_status",
                            "value": {
                                "instance[]": [
                                    {
                                        "key": "humdiity",
                                        "value": {
                                            "double": 5.0
                                        },
                                        "verif": 22222222
                                    },
                                    {
                                        "key": "temp",
                                        "value": {
                                            "double": 70.0
                                        },
                                        "verif": 22222222
                                    }
                                ]
                            },
                            "verif": 22222222
                        },
                        {
                            "key": "environment",
                            "value": {
                                "string[]": []
                            },
                            "verif": 22222222
                        }
                    ]
                },
                "verif": 22222222
            }
        ]
    },
    "verif": 22222222
}

]

I am trying to update the following section of it like adding "aaaa" and "bbb"

        "instance[]": [
            {
                "key": "requires",
                "value": {
                    "string[]": ["aaaa", "bbb"]
                },

I was wondering if there is any built-in library in python that i can use for this goal?

i can filter it out and store it in a list like below, but i am not sure how i can update it.

newl = [d for d in test if d["key"] == "order" ]
print(newl)
#which prints
[{'key': 'order', 'value': {'instance[]': [{'key': 'order_det', 'value': {'instance[]': [{'key': 'requires', 'value': {'string[]': []}, 'verif': 22222222}, {'key': 'status', 'value': {'string[]': []}, 'verif': 22222222}, {'key': 'system_status', 'value': {'string[]': ['sys1.out', 'sys1.checking']}, 'verif': 22222222}, {'key': 'weather_status', 'value': {'instance[]': [{'key': 'humdiity', 'value': {'double': 5.0}, 'verif': 22222222}, {'key': 'temp', 'value': {'double': 70.0}, 'verif': 22222222}]}, 'verif': 22222222}, {'key': 'environment', 'value': {'string[]': []}, 'verif': 22222222}]}, 'verif': 22222222}]}, 'verif': 22222222}]

答案1

得分: 1

你可以使用递归来查找具有指定键的字典。

def get(o, k):
    if isinstance(o, list):
        for x in o:
            if res := get(x, k):
                return res
    elif o['key'] == k:
        return o
    elif nxt := o.get('value', {}).get('instance[]'):
        return get(nxt, k)
o = get(test, 'requires')
if o:
    o['value']['string[]'] += "aaaa", "bbb"
print(test) # test now changed

(Note: I've provided the translated code as requested.)

英文:

You could use recursion to find the dict with the specified key.

def get(o, k):
    if isinstance(o, list):
        for x in o:
            if res := get(x, k):
                return res
    elif o['key'] == k:
        return o
    elif nxt := o.get('value', {}).get('instance[]'):
        return get(nxt, k)
o = get(test, 'requires')
if o:
    o['value']['string[]'] += "aaaa", "bbb"
print(test) # test now changed

huangapple
  • 本文由 发表于 2023年6月5日 04:34:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76402313.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定