【问题标题】:Updating dictionary values using keys and values from lists使用列表中的键和值更新字典值
【发布时间】:2021-03-15 09:35:08
【问题描述】:

我希望能够索引字典并通过使用特定列表中的键并将值写入该列表中的那些键来替换特定键的值。

代码

dicty = {"NDS" : 1, "TCT": 2, "ET" : 3, "ACC" : 4,"Ydist" : 5, "Diam" : 6}


tem = ["NDS", "TCT"]
circ = ["ET", "ACC"]
jit = ["Ydist", "Diam"]


def cal_loop(cal_vers):
    if cal_vers == temp_calibration:
        print("DO TEMP CALIBRATION")
        tem_results = [19,30]
        dict_keys = tem
        dicty[[dict_keys][0]] = tem_results[0]
        print(dicty["NDS"])

temp_calibration = 6


cal_loop(temp_calibration)
print(dicty)

追溯

期望的输出

{'NDS': 19, 'TCT': 2, 'ET': 3, 'ACC': 4, 'Ydist': 5, 'Diam': 6}

#I also want to know how to do both keys in the list given e.g.
{'NDS': 19, 'TCT': 30, 'ET': 3, 'ACC': 4, 'Ydist': 5, 'Diam': 6}

【问题讨论】:

    标签: python dictionary indexing hash key-value


    【解决方案1】:
    tem = ["NDS", "TCT"]
    tem_results = [19,30]
    
    for k, v in zip(tem, tem_results):
        dicty[k] = v
    

    问题在于dicty[[dict_keys][0]] = tem_results[0]。您必须循环考虑这两个列表并更新字典,或者创建一个新字典并使用以下方法更新现有字典:

    dicty.update({k: v for k, v in zip(tem, tem_results)})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-02
      • 2013-11-01
      • 2018-02-11
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      相关资源
      最近更新 更多