简体   繁体   中英

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

I have a list called k_points with tuples [(2.429584911990176, 0.5040720081303796), (3.396089990024489, 9.114060958885277), (5.451196187915455, 5.522005580434297)] which I want as a value in the key-value pair of this dictionary, and I want to append it, while the index will be the key pair. How can I do this? So far, I have:

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

and then I get the list

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

which at least I get the values right but I don't get an index number as a key pair. How can I fic this probelm?

You could go like this:

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

Or just use a dict comprehension:

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

both yield:

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

You mean the following?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM