Python3 天哪,对不起以这种或那种方式可能经常重复的问题。对我来说,操纵名单一直就像一个黑匣子的头痛,我现在已经争斗了一个小时没有结果。
我的表格中有一个列表:
[('John', 'first@email.com'), ('John', 'second@email.com'), ('Jack', 'third@email.com')]
我想将其转换为可迭代的字典(然后我可以使用pymongo将其作为文档批量插入),以便它看起来像这样:
new_posts = [{"sender": "John",
"email": "first@email.com"},
{"sender": "John",
"email": "second@email.com"},
{"sender": "Jack",
"email": "third@email.com"}]
如何以易于阅读和有效的方式实现这一目标?
答案 0 :(得分:2)
你可以尝试
>>> a = [('John', 'first@email.com'), ('John', 'second@email.com'), ('Jack', 'third@email.com')]
>>> [dict([('sender', x[0]), ('email',x[1])]) for x in a]
[{'sender': 'John', 'email': 'first@email.com'}, {'sender': 'John', 'email': 'second@email.com'}, {'sender': 'Jack', 'email': 'third@email.com'}]
这会将列表转换为dict
答案 1 :(得分:1)
data = [('John', 'first@email.com'), ('John', 'second@email.com'), ('Jack', 'third@email.com')]
new_posts = []
for i in range(len(data)):
new_post = {}
new_post["sender"] = data[i][0]
new_post["email"] = data[i][1]
new_posts.append(new_post)
另一种解决方法..
答案 2 :(得分:0)
your_list = [('John', 'first@email.com'), ('John', 'second@email.com'), ('Jack', 'third@email.com')]
your_result = [{'sender': sender, 'email': email} for sender, email in your_list]