将[{},{}]转为dict


经常遇到一种需求,需要把从数据库取出的数据,转为dict对象([{}, {},...]-->dict)。

rs = [{"user_id":111, "name":"abc"}, {"user_id":123, "name":"edf"}]
print dict(map(lambda r:[r["user_id"], r], rs))
>>{111: {'user_id': 111, 'name': 'abc'}, 123: {'user_id': 123, 'name': 'edf'}}

上面看起来比较啰嗦,换一种写法

print dict([r["user_id"], r] for r in rs)

更简洁的写法

{r['user_id'] : r for r in rs}


上篇: IBUS-WARNING Process Key Event failed Timeout was reached 下篇: webpy中auto_application的cookie共享问题