I have list of float values xy = [412.1587, 14.12, 4112.7, 14.0] and also list of keys keys_list = ['x','y'] Expected output a = [{'x': 412.1587, 'y': 14.12}, {'x': 4112.7, 'y': 14.0}]
Thank you for helping me!
CodePudding user response:
I think you mean dictionary as the output. You can merge two lists into a dictionary using the following process.
keys_list = ['x','y']
values = [412.1587, 14.12, 4112.7, 14.0]
output = dict(zip(keys_list, values))
But I think having the same length lists makes more sense for this kind of solution.
CodePudding user response:
Since the requested output is syntactically wrong, I'm proposing a different solution with somewhat similar output, but replacing 'x' and 'y' with unique keys:
xy = [412.1587, 14.12, 4112.7, 14.0]
keys_list = ['x', 'y']
a = [{f"{keys_list[i % len(keys_list)]}{int(i / 2)}": v} for i, v in enumerate(xy)]
print(a)
This will output
{'x0': 412.1587, 'y0': 14.12, 'x1': 4112.7, 'y1': 14.0}
EDIT After reading your comments, you specified you wanted coordinate pairs in a list so here is an updated function. It will also work if you want to add a third dimension ('z') in the keyset.
pairs = []
for i in range(0, len(xy), len(keys_list)):
d = {v: xy[i n] for n, v in enumerate(keys_list)}
pairs.append(d)
print(pairs)
The output is
[{'x': 412.1587, 'y': 14.12}, {'x': 4112.7, 'y': 14.0}]
CodePudding user response:
lets assume float values xy = test_values and keys_list = test_keys
output = {test_keys[i]: test_values[i] for i in range(len(test_keys))}