【问题标题】:How can I append key,value pair to empty dictionary with the index value as the key pair?如何将键、值对附加到以索引值作为键对的空字典中?
【发布时间】:2021-01-19 19:59:31
【问题描述】:

我有一个名为K_Points的列表,带元组[(2.4295849190390176,0.5040720081303796),(3.396089990024489,9.11406095885277),(5.451196187915455,5.52200558043455,5.522005580434297)]我想要在这个词典的键值对中的值,我想要追加它,而索引将是密钥对。我怎样才能做到这一点? 到目前为止,我有:

dict_self = {}
k_points = [(2.429584911990176, 0.5040720081303796), (3.396089990024489, 9.114060958885277), (5.451196187915455, 5.522005580434297)]

for points in k_points:
     dict_self.update({enumerate(k_points) : points})

然后我得到列表

{<enumerate object at 0x0000026C7A0B36C0>: (2.429584911990176, 0.5040720081303796), <enumerate object at 0x0000026C7A0B3678>: (3.396089990024489, 9.114060958885277), <enumerate object at 0x0000026C7A0B3630>: (5.451196187915455, 5.522005580434297)}

至少我得到了正确的值,但我没有得到索引号作为密钥对。我该如何解决这个问题?

【问题讨论】:

    标签: python dictionary iterator key-value


    【解决方案1】:

    你的意思是以下?

    d = {} 
    for i in range(len(k_points)):
        d[i] = points[i] 
    

    【讨论】:

      【解决方案2】:

      你可以这样:

      for i, point in enumerate(k_points):
           dict_self[i] = point
      

      或者只使用字典理解:

      dict_self = {i : point for i, point in enumerate(k_points)}
      

      两者都有:

       {0: (2.429584911990176, 0.5040720081303796),
       1: (3.396089990024489, 9.114060958885277),
       2: (5.451196187915455, 5.522005580434297)}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-17
        • 2020-11-23
        • 1970-01-01
        • 2021-12-24
        相关资源
        最近更新 更多