I have a list of dictionaries that looks something like this->
list = [{"id":1,"path":"a/b", ........},
{"id":2,"path":"a/b/c", ........},
{"id":3,"path":"a/b/c/d", ........}]
Now I want to create a dict of path to id mapping. That should look something like this->
d=dict()
d["a/b"] = 1
d["a/b/c"] = 2
d["a/b/c/d"] = 3
how to create it in pythonic way
像这样尝试:
d = {i['path']:i['id'] for i in list}
也许是这样的:
d = {x["path"]: x["id"] for x in list_of_dicts}
Something like that maybe?
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
This is the output:
{'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"])
OUTPUT :
{'a/b': 1, 'a/b/c': 2, 'a/b/c/d': 3}
1
2
3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.