-3

I need to store multiple values inside of one variable, so i thought the best way of doing something like this would be with a dictionary. I'm just wondering how I would do this.

I want to pass in in first input message id, where in a .json file it will create this

"(message id)" = {}

basically creating a dictionary with no content next. Then I want to be able to pass in value1 and value2 and put them in the dictionary like this:

"(message id)" = {value1 = value2}

And then I should be able to repeat this over and over again so that i have a value3 = value4 etc

I only know how to use json to do simple dictionaries like this:

{
   value1 = value2,
   value3 = value4
}

I just want to be able to put the dictionary into the variable. Thanks. This is all for a discord bot reaction role so i can make message id the message id and then the value 1 and 2's are the reaction and the role it gives

Gamopo
  • 1,600
  • 1
  • 14
  • 22
Remi_Zacharias
  • 288
  • 2
  • 4
  • 16
  • Does this answer your question? [How can I add new keys to a dictionary?](https://stackoverflow.com/questions/1024847/how-can-i-add-new-keys-to-a-dictionary) – Gamopo Oct 06 '20 at 14:12
  • The answer is what I'm looking for, but I don't think it was adding keys in .json. I'm using .json files for this – Remi_Zacharias Oct 06 '20 at 14:15
  • Does this help: [How to add a key-value to JSON data retrieved from a file with Python](https://stackoverflow.com/questions/23111625/how-to-add-a-key-value-to-json-data-retrieved-from-a-file-with-python) – DarrylG Oct 06 '20 at 14:22

1 Answers1

0
import json

with open("data.json") as f:
    data = json.load(f)

data['message_id'] = {}
# add keys to message_id like this
data['message_id']['key1'] = {} #nested dictionary
data['message_id']['key1']['another_key'] = 'something'
# it will be like {"message_id": {"key1": {"another_key": "something"}}}

with open('data.json', 'w') as f:
    f.write(data, f, indent=4) # indent for nice visualization
Just for fun
  • 4,102
  • 1
  • 5
  • 11