简体   繁体   English

从多个列表创建字典,其中每个列表没有一个键的值,但每个列表都有所有键的值

[英]create dictionary from multiple lists, where each list has not the values for one key, but each list has values for all keys

I have lists like:我有如下列表:

key1=['A','B','C']
key2=['X','Y','Z']
entry1=['x1','y1','z1']
entry2=['x2','y2','z2']
entry3=['x3','y3','z3']

I want my dictionary to have items in the following format:我希望我的字典具有以下格式的项目:

mydict={'A':{'X':'x1','Y':'y1','Z':'z1'},'B':{'X':'x2','Y':'y2','Z':'z2'},'C':{'X':'x3','Y':'y3','Z':'z3'}}

Can someone help??有人可以帮忙吗??

It's easier if you start by making the three entry lists into a single list.如果您从将三个entry列表变成一个列表开始,会更容易。 Then you can zip that list with key1 to get:然后你可以用key1列出zip得到:

entries = [entry1, entry2, entry3]
mydict = {
    k1: {k2: e for k2, e in zip(key2, entry)}
    for k1, entry in zip(key1, entries)
}

Here is you can use a nested dictionary comprehension:这是您可以使用嵌套字典理解的:

key1=['A','B','C']
key2=['X','Y','Z']
entry1=['x1','y1','z1']
entry2=['x2','y2','z2']
entry3=['x3','y3','z3']

entries = [entry1, entry2, entry3]

my_dict = {k1:{k2:v for k2,v in zip(key2,entry)} for k1,entry in zip(key1,entries)}

print(my_dict)

Output: Output:

{'A': {'X': 'x1', 'Y': 'y1', 'Z': 'z1'}, 'B': {'X': 'x2', 'Y': 'y2', 'Z': 'z2'}, 'C': {'X': 'x3', 'Y': 'y3', 'Z': 'z3'}}

暂无
暂无

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

相关问题 如何从字典列表中创建三个单独的值列表,其中每个字典都有三个键 - How to create three separate lists of values from a list of dictionaries where each dictionary has three keys 如何从列表中创建字典,其中每个元素的计数是键,值是相应元素的列表? - How to create a dictionary from a list where the count of each element is the key and values are the lists of the according element? 从一组列表创建字典,其中键是每个列表的名称,值是列表 - Creating a dictionary from a group of lists, where the keys are the name of each list and the values are the lists 创建一个 Python 字典,其中每个键都有一个列表作为值 - create a Python dictionary where for each key has a list as the value 从具有分配给每个键的多个值的字典创建数据帧 - Creating Dataframe from dictionary that has multiple values assigned to each key Python Pandas:从具有列表列表值的字典创建 DataFrame - Python Pandas: Create DataFrame from dictionary that has values of list of lists Pandas - groupby,其中每行都有多个存储在列表中的值 - Pandas - groupby where each row has multiple values stored in list 将项目列表转换为多个字典,其中每个键只有列表中的一个值 - Turn a list of items into multiple dictionaries where each key has only one value from the list PySpark - 从字典中创建一个 Dataframe,其中包含每个键的值列表 - PySpark - Create a Dataframe from a dictionary with list of values for each key 在python中,如何找到字典中的值之和? 每个键都有多个值 - In python, how do I find the sum of values in a dictionary? Where each key has multiple values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM