繁体   English   中英

从字典列表创建字典

[英]creating a dict from list of dicts

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

  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方式创建它

像这样尝试:

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

也许是这样的:

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

也许是这样的?

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}

_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"])

输出

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

暂无
暂无

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

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