如何将键值对附加到以索引值作为键对的空字典?

How can I append key,value pair to empty dictionary with the index value as the key pair?

i有一个列表,称为k_points,带有成员[(2.429584911990176,0.5040720081303796),(3.396089990024489,9.11406060958885277)字典,我想追加它,而索引将是密钥对。我怎样才能做到这一点? 到目前为止,我有:

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)}

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

你可以这样做:

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)}

你的意思是下面的?

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