Home > Back-end >  Python add new key/value to list of dictionaries where key matches a value
Python add new key/value to list of dictionaries where key matches a value

Time:06-01

I have the following list of dictionaries:

data = {
            "coms": [
                {
                    "eid": "8b1fac95-edc9-43c9-a136-4b25939cedc1",
                    "nid": "8d769a38-a3e2-4bf4-96f4-c17999e6b5a3",
                },
                {
                    "eid": "b8b30d9f-fe5f-4eba-a1cf-56876b82aa4e",
                    "nid": "3265b9ac-67ee-46e4-ab40-d509e90a378b",

                }
            ]
        }

And I have a matching key (match_key) and the value (nsrid):

nsrid = "b9ec3267-5b77-4f87-aeb5-cd11c28bd518"
match_nid = "8d769a38-a3e2-4bf4-96f4-c17999e6b5a3"

I was wondering how I can create a new key/value {'nsrid:' nsrid} pair in a dictionary in a list where match_nid matches a nid in my list of dictionaries, so like this:

data = {
            "coms": [
                {
                    "eid": "8b1fac95-edc9-43c9-a136-4b25939cedc1",
                    "nid": "8d769a38-a3e2-4bf4-96f4-c17999e6b5a3",
                    "nsrid": "b9ec3267-5b77-4f87-aeb5-cd11c28bd518",
                },
                {
                    "eid": "b8b30d9f-fe5f-4eba-a1cf-56876b82aa4e",
                    "nid": "3265b9ac-67ee-46e4-ab40-d509e90a378b",

                }
            ]
        }

There will be a chance that nsrid may change as part of a looping mechanism, and the second time around the nsrid may relate to the second dictionary nid, so I need to keep the previous update, such as:

nsrid = "3797ce00-3e50-4286-a113-38bd61030fdc"
match_nid = "3265b9ac-67ee-46e4-ab40-d509e90a378b"
data = {
            "coms": [
                {
                    "eid": "8b1fac95-edc9-43c9-a136-4b25939cedc1",
                    "nid": "8d769a38-a3e2-4bf4-96f4-c17999e6b5a3",
                    "nsrid": "b9ec3267-5b77-4f87-aeb5-cd11c28bd518",
                },
                {
                    "eid": "b8b30d9f-fe5f-4eba-a1cf-56876b82aa4e",
                    "nid": "3265b9ac-67ee-46e4-ab40-d509e90a378b",
                    "nsrid": "3797ce00-3e50-4286-a113-38bd61030fdc",

                }
            ]
        }

CodePudding user response:

Does this solve your problem ?

data = {
            "coms": [
                {
                    "eid": "8b1fac95-edc9-43c9-a136-4b25939cedc1",
                    "nid": "8d769a38-a3e2-4bf4-96f4-c17999e6b5a3",
                },
                {
                    "eid": "b8b30d9f-fe5f-4eba-a1cf-56876b82aa4e",
                    "nid": "3265b9ac-67ee-46e4-ab40-d509e90a378b",

                }
            ]
        }

nsrid = "b9ec3267-5b77-4f87-aeb5-cd11c28bd518"
match_nid = "8d769a38-a3e2-4bf4-96f4-c17999e6b5a3"

for index in range(len(data["coms"])):
    if data["coms"][index]["nid"] == match_nid:
        data["coms"][index]["nsrid"] = nsrid
  • Related