我的程式中使用了三個字典,并且需要能夠向三個字典中的任何一個添加或洗掉一個專案。如何通過使用變數告訴程式將專案添加到哪個字典?我不能簡單地輸入“DictName[NewKey] = NewValue”,因為它取決于用戶選擇的字典。
例子:
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
我的問題是我不能使用變數來呼叫 dict 并更改編輯它。
uj5u.com熱心網友回復:
字典詞典怎么樣?例如,如果用戶輸入字串“Dict1”,您可以通過以下方式取消參考該特定字典:
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
uj5u.com熱心網友回復:
使用字典的字典:
super_dict = {
"Dict1": {"Key1": "Value1"},
"Dict2": {"Key2": "Value2"},
"Dict3": {"Key3": "Value3"}
}
然后你可以通過這種方式訪問??它們:
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"
uj5u.com熱心網友回復:
通過新的字典管理它們
Dict1 = {"Key1": "Value1"}
Dict2 = {"Key2": "Value2"}
Dict3 = {"Key3": "Value3"}
dicts = {
"1": Dict1,
"2": Dict2,
"3": Dict3,
}
var = input("Please choose a dictionary") # 1 or 2 or 3
print("Add item to", var)
dicts[var][key4] = Value 4
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/451547.html
下一篇:如何在函式內正確使用While?
