Home > Software engineering >  Python setting dynamic value to dictionary
Python setting dynamic value to dictionary

Time:09-16

I have following sample dict format which i need to build where number, description will populate dynamically.

{
    "method": "POST",
    "headers": {},
    "body": {
      "message": {
        "messageId": 22,
        "messageVersion": 3
      },
      "number": 1112223333,
      "description": "Test Message"
    }
}

There is one file which contains number, description e.g. data.dat which contains following


1, mydecription1  
2 , mydecription2
so on... 

Is there anyway to achieve this where i am replacing the number, description after reading the file..

CodePudding user response:

I think it depends on how you'll read the file. Will you use something like this?

import pandas
df =  pandas.read_csv("path_to_file")

Then with that you could iterrows like so:

for row in df.iterrows():
     your_dict["number"] = row["number"]
     your_dict["description" = row["description"]

But guess we need more info about your constraints.

CodePudding user response:

I'm assuming you're not asking us how to read your data file, and have already figured that out. I'm also assuming a lot about your workflow here. Do you need all of these dictionaries at once, or one at a time? It's not clear from your post so this is a possible approach:

from copy import deepcopy  # std lib, no need to install anything


template = {"method": "POST",
            "headers": {},
            "body": {"message": {"messageId": 22, "messageVersion": 3}}}


# Read in all your num, desc pairs
data = []
with open("my_file.DAT", "r") as f:
    for line in f.readlines():
        # get number and description
        data.append(dict(number=num, description=desc))


for data_dict in data:
    template_copy = deepcopy(template)
    template_copy["body"].update(data_dict)
    # do something with your now-complete dictionary
  • Related