Home > Software engineering >  How to get value based on another key on list of dict?
How to get value based on another key on list of dict?

Time:06-23

I have list and a dict like this:

 my_ls = [{"type": "A", "value": "100"}, {"type": "B", "value": "200"}, {"type": "C", "value": "300"}, {"type": "D", "value": "700"}]

 my_dict =
  {
   "A":"A Name"
   "B": "B Name",
   "C": "C Name",
   "D": "D Name"
  }

Now I want dict like this based on above these two list and dict:

  {"A Name": "Type A value from list i.e 100",
   "B Name": "Type B value from list i.e 200",
   "C Name": "Type C value from list i.e 300",
   "D Name": "Type D value from list i.e 700"
}
           

If my_list type and my_dict key has same name then get the value of this type from list.

CodePudding user response:

Simply iterate over my_ls and check if "type" is present in the keys of my_dict, if so add to your dictionary.

ans = {}
for ls_val in my_ls:
    if ls_val["type"] in my_dict.keys():
        ans_key = my_dict[ls_val["type"]]
        ans_val = ls_val["value"]
        ans[ans_key] = ans_val
print(ans)

{'A Name': '100', 'B Name': '200', 'C Name': '300', 'D Name': '700'}

CodePudding user response:

Try using generative

mapping = {item["type"]: item["value"] for item in my_ls}
res = {my_dict[k]: "Type {} value from list i.e {}".format(k, v) for k, v in mapping.items() if my_dict.get(k)}
print(res)

# {'A Name': 'Type A value from list i.e 100', 'B Name': 'Type B value from list i.e 200', 'C Name': 'Type C value from list i.e 300', 'D Name': 'Type D value from list i.e 700'}

CodePudding user response:

First, you can do preprocessing on my_ls and create a dict then create the desired output by the combination of my_dict and preprocessing dict:

>>> tmp_dict = {ml["type"]: ml["value"] for ml in my_ls}
>>> {v_md: f"Type {k_md} value from list i.e {tmp_dict[k_md]}" for k_md, v_md in my_dict.items()}

{'A Name': 'Type A value from list i.e 100',
 'B Name': 'Type B value from list i.e 200',
 'C Name': 'Type C value from list i.e 300',
 'D Name': 'Type D value from list i.e 700'}
  • Related