算法 - 一道python题目:如何把元组编程字典?
ringa_lee
ringa_lee 2017-04-18 09:06:51
0
5
708

问题:

我有一个元组列表:

现在我想把这组元组变成字典的列表,类似的效果是这样:

meat = [
    {
    "地区词":"深圳福田区",
    "品牌词":"TTM全身体检",
    "疑问词":"地址怎么走",
    "价格词":"价格要多少钱"
    },
    {
    "地区词":"深圳保安区",
    "品牌词":"TTM全身体检",
    "疑问词":"地址怎么走",
    "价格词":"要做多少项目"
    },
    .....
        ]

有什么比较方便的方法?

ringa_lee
ringa_lee

ringa_lee

reply all(5)
刘奇

@dokelung’s method can be more concise

names = 'area brand question price'.split()
lst = [dict(zip(names, t)) for t in tlst]
大家讲道理
names = 'area brand question price'.split()
lst = [{name:value for name, value in zip(names, t)} for t in tlst]

Test:

tlst = [('a1','b1','q1','p1'),
        ('a2','b2','q2','p2'),
        ('a3','b3','q3','p3')]
 
names = 'area brand question price'.split()
lst = [{name:value for name, value in zip(names, t)} for t in tlst]

print(lst)

Result:

[{'brand': 'b1', 'area': 'a1', 'question': 'q1', 'price': 'p1'}, {'brand': 'b2', 'area': 'a2', 'question': 'q2', 'price': 'p2'}, {'brand': 'b3', 'area': 'a3', 'question': 'q3', 'price': 'p3'}]

Questions I answered: Python-QA

迷茫

Simple way of writing: (a is an array of tuples)

meat = [{'地区词':t[0], '品牌词':t[1], '疑问词':t[2], '价格词':t[3]} for t in a]

Of course you can also try the mapping method, which is not covered here

Peter_Zhu

In order to forcefully show off, use $lambda$ expression to write:

list(map(lambda x: {'地区词':x[0], '品牌词':x[1], '疑问词':x[2], '价格词':x[3]}, a))

Please ignore my answer. . .

迷茫

The correct solution upstairs is to form a separate dictionary, and then call the append of the array and it will be ok

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template