rethinkdb中是否有任何内置机制将对象数组转换为键值?

时间:2018-07-09 13:43:45

标签: rethinkdb rethinkdb-python

我想转型

[{"id": 1, "name": "some_name_1", "alias": "alias1"}, {"id": 2, "name": "some_name_2", alias: "alias2"}, {"id": 3, "name": "some_name_3", "alias": "alias3"}] 

进入

{"1": {"id": 1, "name": "some_name_1", "alias": "alias1"}, "2": {"id": 2, "name": "some_name_2", alias: "alias2"}, "3": {"id": 3, "name": "some_name_3", "alias": "alias3"}}

1 个答案:

答案 0 :(得分:0)

您可以使用 List Comprehension 实现此目的。

代码:

dict = [{"id": 1, "name": "some_name_1", "alias": "alias1"}, {"id": 2, "name": "some_name_2", "alias": "alias2"}, {"id": 3, "name": "some_name_3", "alias": "alias3"}]
print (*[{str(i+1):x} for i,x in enumerate(dict)])

编辑:如果应显示字典键而不是索引,

print (*[{x["id"]:x} for x in dict])

输出:

{'1': {'id': 1, 'name': 'some_name_1', 'alias': 'alias1'}} {'2': {'id': 2, 'name': 'some_name_2', 'alias': 'alias2'}} {'3': {'id': 3, 'name': 'some_name_3', 'alias': 'alias3'}}