简体   繁体   中英

Generate Key value pairs from two lists in python

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?

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

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