以元组为键访问字典的键值

Bar*_*onk 2 python dictionary

我有dict这样的字典,以元组为键:

 dict = { (1, 1): 10, (2,1): 12} 
Run Code Online (Sandbox Code Playgroud)

并尝试像这样访问它:

new_dict = {}
for key, value in dict: 
    new_dict["A"] = key[0]
    new_dict["B"] = key[1]
    new_dict["C"] = value
Run Code Online (Sandbox Code Playgroud)

但它失败了,因为key似乎没有解析为元组。正确的方法是什么?

ac2*_*c24 5

要迭代键值对,请使用.items()dict 的方法。

另外,给字典起一个名字,my_dict以避免覆盖内置的dict.

new_dict = {}
for key, value in my_dict.items(): 
    new_dict["A"] = key[0]
    new_dict["B"] = key[1]
    new_dict["C"] = value
Run Code Online (Sandbox Code Playgroud)