从字典列表中创建字典

时间:2019-02-21 11:27:42

标签: python list dictionary

我有一个字典列表,看起来像这样->

  list =  [{"id":1,"path":"a/b", ........},
           {"id":2,"path":"a/b/c", ........},
           {"id":3,"path":"a/b/c/d", ........}]

现在我要创建一个ID映射路径的字典。 看起来应该像这样->

   d=dict()
   d["a/b"] = 1
   d["a/b/c"] = 2
   d["a/b/c/d"] = 3

如何以pythonic方式创建

4 个答案:

答案 0 :(得分:0)

尝试这样:

d = {i['path']:i['id'] for i in list}

答案 1 :(得分:0)

也许像这样:

d = {x["path"]: x["id"] for x in list_of_dicts}

答案 2 :(得分:0)

诸如此类的东西?

list =  [{"id":1,"path":"a/b", "test":"1"},{"id":2,"path":"a/b/c", "test":"2"}, {"id":3,"path":"a/b/c/d", "test":"3"}]
d={}
for i in list:
    d[i['path']]=d['id']
print d

这是输出:

  

{'a / b / c':2,'a / b / c / d':3,'a / b':1}

答案 3 :(得分:0)

SELECT
    MONTH(p_purch_stock.date) AS mnth_no,
    p_parts.catetype,
    SUM(p_purch_stock.Netamount) AS sale,
    SUM(  p_purch_return.unit_price * p_purch_return.return_qty  ) AS return_amount
FROM
    p_purch_stock
INNER JOIN p_parts ON p_purch_stock.part_no = p_parts.Part_no
INNER JOIN p_purch_return ON p_purch_stock.stock_id=p_purch_return.stock_id
WHERE
    (p_purch_stock.cate_type = 'IMC-imported' OR p_purch_stock.cate_type = 'IMC' OR p_purch_stock.cate_type = 'IMC-Local' ) 
    AND DATE_FORMAT(p_purch_stock.date, '%Y-%m-%d') BETWEEN '2019-01-01' AND '2019-12-31'
    AND DATE_FORMAT(  p_purch_return.datetime,   '%Y-%m-%d'    ) BETWEEN '2019-01-01' AND '2019-12-31'
GROUP BY
    MONTH(p_purch_stock.date),
    p_parts.catetype

输出

_lst =  [{"id":1,"path":"a/b"},
           {"id":2,"path":"a/b/c"},
           {"id":3,"path":"a/b/c/d"}]

d = {i["path"]: i["id"] for i in _lst}

print(d)
print(d["a/b"])
print(d["a/b/c"])
print(d["a/b/c/d"])