简体   繁体   English

使用单个列表(充当键)映射多个列表(充当值)以在python中创建字典

[英]Map multiple lists(acting as values) with a single list(acting as key) to create a dictionary in python

headers = ['id', 'product', 'plan']

values = [['1', 'abc', '123'],['2', 'efg', '1234'],['3', 'ijk', '890']]

data = []

for entries in values:
    data.append(dict(itertools.izip(headers, entries)))

The common pattern for this type of data abstraction is a list of dicts which easily translates to JSON - an array of objects. 此类数据抽象的常见模式是字典列表,这些字典可轻松转换为JSON(对象数组)。

import pprint

headers = ['id', 'product', 'plan']

values = [
    ['1', 'abc', '123'],
    ['2', 'efg', '1234'],
    ['3', 'ijk', '890'],
]

list_of_dicts = [dict(zip(headers, row)) for row in values]

pprint.pprint(list_of_dicts)

output 产量

[{'id': '1', 'plan': '123', 'product': 'abc'},
 {'id': '2', 'plan': '1234', 'product': 'efg'},
 {'id': '3', 'plan': '890', 'product': 'ijk'}]

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

相关问题 Map 来自两个不同列表的多个值到 Python 字典键 - Map Multiple Values to Python Dictionary Key from Two Different Lists 将多个值列表映射到python字典中的键列表? - Map multiple lists of values to a list of keys in a python dictionary? Python如何针​​对字典中的单个键创建多个值 - Python How to create multiple values against a single key in dictionary 将列表列表转换为具有多个键值的字典 - Converting list of lists to a dictionary with multiple values for a key Python:创建列表列表作为字典值 - Python: Create list of lists as dictionary values 包含同一键下的多个列表列表的单个字典。 希望将同一键下的所有值组合到一个列表中 - single dictionary containing multiple list of lists under the same key. Looking to combining the all values under the same key into a single list 如何将多个键转换为单个字典并在 python 中创建每个键具有多个值的字典 - How convert multiple keys into single of dictionary and create Dictionary with multiple values per key in python 将多个值添加到python字典中的单个键 - Add multiple values to single key in python dictionary 具有多个值的 Python 字典单键可能吗? - Python dictionary single key with multiple values possible? 随机组件行为异常的列表列表 - List of lists with random component acting oddly
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM