Home > Back-end >  How can I call .format() from a dictionary when I can only access the string values of that dictiona
How can I call .format() from a dictionary when I can only access the string values of that dictiona

Time:04-14

I have a program where the user uploads a JSON file and then the program turns it into a dictionary and then does some math on it. Before that math I want to access items of the dictionary within the actual dictionary. Essentially this would be a popup message that says something along the lines of "The values uploaded from the JSON file are x, y, and z".

   example_dict = {
        "first_item": 11,
        "second_item": "this is a sentence",
        "message_item": "'Second item was {}, and the first item is {}'.format(example_dict['second_item'], example_dict['first_item])"
    }

print(example_dict)

I already have the uploading from a JSON part working, this is an example of what I would like to have happen.

Yes I am aware that I can update the dictionary values from outside of it, but, at the end, I have to rewrite the dictionary back to the JSON file, so I am essentially then hard coding it. Whatever is in that dictionary is rewritten. For example I could do,

message = "Second item was {}, and the first item is {}".format(example_dict['second_item'], example_dict['first_item'])
example_dict['message_item'] = message

This the means that, if the user wants to edit the JSON file to have it only show the first value, they cannot do that.

CodePudding user response:

You can use eval or exec functions in python to execute arbitrary python code.

example_dict = {
        "first_item": 11,
        "second_item": "this is a sentence",
        "message_item": "'Second item was {}, and the first item is {}'.format(example_dict['second_item'], example_dict['first_item])"
    }

message = eval(example_dict['message_item'])
print(message)

CodePudding user response:

I was able to get my desired output using the .format(**dictionary) method. I found it in another question and was able to tweak it to make it work for my specific use case. Working code below.

example_dict = {
    "first_item": 11,
    "second_item": "this is a sentence",
    "message_item": "Second item was {second_item}, and the first item is {first_item}"
}


message = example_dict['message_item'].format(**example_dict)
print(message)
  • Related