Home > database >  Generate Key value pairs from two lists in python
Generate Key value pairs from two lists in python

Time:09-06

I have 2 lists:

list1 = ["Mar 04", "Mar 05", "Mar 06", "Mar 07", "Mar 08", "Mar 09"]
lsit2 = [72888494.4, 151676281, 142677, 5865.698, 107451, 945203.08]

I want to generate key value pairs which look like this:

lst = [
    {"x": "Mar 04", "y": "72888494.4"},
    {"x": "Mar 05", "y": "151676281"},
    {"x": "Mar 06", "y": "142677"},
]

How should I do it?

CodePudding user response:

You can use zip:

lst = [{'x': list1_element, 'y': list2_element} for list1_element, list2_element in zip(list1, list2)]

Or you can do it without any functions:

lst = []
for i in range(len(list1)):
    lst.append({'x': list1[i], 'y': list2[i]})
  • Related