【问题标题】:Access key values of dictionary with tuple as key [duplicate]以元组为键访问字典的键值[重复]
【发布时间】:2020-05-12 21:47:56
【问题描述】:

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

 dict = { (1, 1): 10, (2,1): 12} 

并尝试像这样访问它:

new_dict = {}
for key, value in dict: 
    new_dict["A"] = key[0]
    new_dict["B"] = key[1]
    new_dict["C"] = value

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

【问题讨论】:

  • 如果你使用 Python 3,你可以试试for key, value in dict.items():

标签: python dictionary


【解决方案1】:

要遍历键值对,请使用字典的.items() 方法。

另外,给字典命名为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

【讨论】:

    猜你喜欢
    • 2018-01-14
    • 2013-07-11
    • 1970-01-01
    • 2021-09-16
    • 2012-02-20
    • 2011-09-05
    • 2018-05-29
    • 2012-03-23
    • 1970-01-01
    相关资源
    最近更新 更多