Home > Net >  is there any way in python to create list using key value pairs
is there any way in python to create list using key value pairs

Time:12-15

how to create a list of key value pairs in python???

I have these two lists:

x = [1,2,3,4,5]
y = [11,12,13,14,15]

I have tried this code:

l = {i:{'x': x[i], 'y': y[i]} for i in range(len(x))}
print(l)

output I am getting:

{0: {'x': 1, 'y': 11}, 1: {'x': 2, 'y': 12}, 2: {'x': 3, 'y': 13}, 3: {'x': 4, 'y': 14}, 4: {'x': 5, 'y': 15}}

expected output:

[0: {'x': 1, 'y': 11}, 1: {'x': 2, 'y': 12}, 2: {'x': 3, 'y': 13}, 3: {'x': 4, 'y': 14}, 4: {'x': 5, 'y': 15}]

CodePudding user response:

Maybe you need this

x = [1,2,3,4,5]
y = [11,12,13,14,15]

l = [{i:{'x': x[i], 'y': y[i]}}for i in range(len(x))]
print(l)

CodePudding user response:

The closest you can get to the expected output is an array which contains dictionaries it would look like this.

x = [1,2,3,4,5]
y = [11,12,13,14,15]
array = []
for i in len(x):
    array.append({'x' : x[i], 'y' : y[i]}) 

Output will be:

[{'x': 1, 'y': 11}, {'x': 2, 'y': 12}]

You can access an element like this:

array[0]['x'] = 1
array[1]['y'] = 12
  • Related