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

时间:2017-03-16 22:12:16

标签: python python-2.7 python-3.x dictionary

python中是否还有一种优雅的方式可以从dictionarylist创建cs line除了循环?

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'}}

2 个答案:

答案 0 :(得分:5)

您可以将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'}}

答案 1 :(得分:3)

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.

Implementing a bitfield using java enums中了解字典理解。