1

I have three dictionaries being used in my program and need to be able to add or remove an item to any of the three dicts. How do I tell the program which dict to add the item to through the use of a variable? I can't simply put "DictName[NewKey] = NewValue" because it depends on which dict the user has chosen.

Example:

Dict1 = {"Key1": "Value1"}
Dict2 = {"Key2": "Value2"}
Dict3 = {"Key3": "Value3"}

var = input("Please choose a dictionary") #Dict1, Dict2, or Dict3

print("Add item to", var)
var[Key4] = Value 4

My issue is that I cant use the variable to call on the dict and change edit it.

EHam
  • 13
  • 2

4 Answers4

0

Use a dict of dicts:

super_dict = {
    "Dict1": {"Key1": "Value1"},
    "Dict2": {"Key2": "Value2"},
    "Dict3": {"Key3": "Value3"}
}

Then you can access them that way:

var = input(f"Please choose a dictionary: {', '.join(super_dict.keys())}") #Dict1, Dict2, or Dict3

print("Add item to", var)
super_dict[var]["Key4"] = "Value 4"
lumalot
  • 141
  • 10
0

How about a dictionary of dictionaries? If the user enters the string "Dict1", for example, you can de-reference that particular dictionary this way:

Dict1 = {"Key1": "Value1"}
Dict2 = {"Key2": "Value2"}
Dict3 = {"Key3": "Value3"}

dict_of_dicts = {
    "Dict1": Dict1,
    "Dict2": Dict2,
    "Dict3": Dict3,
}

print(dict_of_dicts["Dict1"]["Key1"])
Value1
rhurwitz
  • 2,557
  • 2
  • 10
  • 18
0

Using a new dictionary of dictionaries like the previous answers works well, but if there are a constant amount of dictionaries you can use a simple if-elif-else statement. Of course, if there are varying numbers of dictionaries then it is better to use a dictionary of dictionaries. An if-elif-else statement example follows:

Dict1 = {"Key1": "Value1"}
Dict2 = {"Key2": "Value2"}
Dict3 = {"Key3": "Value3"}

var = input("Please choose a dictionary") #Dict1, Dict2, or Dict3

print("Add item to", var)
if var == "Dict1":
    # do what you want to Dict 1 here
elif var == "Dict2":
    # do what you want to Dict 2 here
else:
    # do what you want to Dict 3 here
  • 1
    Honestly, I can't believe I didn't think of this, thank you. But to keep things organized and easier to read I made use of the subdictionary method which worked well. – EHam Mar 29 '22 at 05:14
0

This globals() method works well in creating variable name dynamically. But its looks a bit complicated. Dictionary of Dictionary method is the cleaner one for your program. You can read more on How can you dynamically create variables?

Dict1 = {"Key1": "Value1"}
Dict2 = {"Key2": "Value2"}
Dict3 = {"Key3": "Value3"}

var = input("Please choose a dictionary: ") # 1 or 2 or 3
globals()[f"Dict{var}"] [f"Key{int(var)+1}"]= f"value{int(var)+1}"
print(globals()[f"Dict{var}"]) 
logi
  • 66
  • 1
  • 1
  • 6