简体   繁体   English

从 python 中的两个列表生成键值对

[英]Generate Key value pairs from two lists in python

I have 2 lists:我有 2 个列表:

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 :您可以使用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]})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从Python中的键/值对自动生成INSERT查询 - Automatically generate INSERT query from key/value pairs in Python 从python中的两个列表创建特定对 - Create specific pairs from two lists in python 如何将 python 中的两个字典列表与可能不同的键值对合并? - How can I merge two lists of dicts in python with potentially different key-value pairs? 将两个列表的元素组合为字典中的key:value对会出错。 Python 3x - Combining elements of two lists as key:value pairs in a dictionary goes wrong. Python 3x Python TypeError:将两个列表的值映射到新的一个容器列表中的键值对 - Python TypeError: Mapping the values of two lists into key-value pairs in a new one container list Python 生成器:如何根据用户输入(要打印多少对)从两个不同的列表中生成对 - Python Generator: How do I generate pairs from two different lists based on user input (of how many pairs to print) 从基于两个具有唯一元素的列表的字典中获取排序的键值对 - Getting sorted key value pairs from a dictionary based on two lists with unique elements 在Python中将两个库仑变成键值对 - turn two coulmns into key value pairs in python Python比较两个键/值对 - Python Compare Two Key/Value Pairs 在没有 Itertools 的情况下从两个列表生成唯一的对 - Generate Unique Pairs From Two Lists Without Itertools
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM