简体   繁体   English

从列表和逗号分隔的行创建python字典

[英]creating a python dictionary from a list and comma separated line

Is there a more elegant way in python to create a dictionary from a list and a cs line besides a loop? python ,除了循环之外,还有一种更优雅的方法可以从listcs line创建dictionary吗?

my_master_list = ["ABC", "DEF", "GHI"]
my_list = ["field1", "field2", "field3"]
my_line = "test1,test2,test3"
my_dict = {}

for x in my_master_list:
    my_dict[x] = {}
    line_parts = my_line.split(",")
    n = 0
    for y in my_list:
        my_dict[x][y] = line_parts[n]
        n +=1

print my_dict
# {'ABC': {'field2': 'test2', 'field3': 'test3', 'field1': 'test1'}, 'GHI': {'field2': 'test2', 'field3': 'test3', 'field1': 'test1'}, 'DEF': {'field2': 'test2', 'field3': 'test3', 'field1': 'test1'}}

You can use zip with a dictionary comprehension : 您可以将zip字典理解一起使用

# construct the inner dictionary 
d = dict(zip(my_list, my_line.split(",")))

# construct the outer dictionary, if you don't want to make copies, you can use 
# {master_key: d ... } directly here just keep in mind they are referring to the same 
# object in this way
{master_key: d.copy() for master_key in my_master_list}

#{'ABC': {'field1': 'test1', 'field2': 'test2', 'field3': 'test3'},
# 'DEF': {'field1': 'test1', 'field2': 'test2', 'field3': 'test3'},
# 'GHI': {'field1': 'test1', 'field2': 'test2', 'field3': 'test3'}}
d = {x:dict(zip(my_list, my_line.split(','))) for x in my_master_list}
        ^   ^                      ^
        |   |                     [1]--- creates a list from the string
        |   |
        |  [2]--- creates a tuple from two lists
        |
       [3]--- creates a dictionary from the tuples (key, value)
 ^
 |
[4] The overall expression is a dictionary comprehension.

Read about dict comprehensions in PEP274 . 阅读有关PEP274中的 dict理解的信息

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM