[英]Python 3: list of 2 elements into dictionary
Python3 OMG, sorry for a probably often repeated question in one way or another. Python3 OMG,对于这种或那种可能经常重复的问题感到抱歉。 For me, manipulating lists has always been like a black box of headaches, and I've been battling for an hour now with no results.
对我来说,操纵名单一直就像一个黑匣子的头痛,我一直在争斗一个小时,没有结果。
I have a list in the form: 我在表格中有一个清单:
[('John', 'first@email.com'), ('John', 'second@email.com'), ('Jack', 'third@email.com')]
I would like to transform this into an iterable dictionary (that I could then bulk insert as a document using pymongo) so that it looks like this: 我想将其转换为可迭代的字典(然后我可以使用pymongo将其作为文档批量插入),以便它看起来像这样:
new_posts = [{"sender": "John",
"email": "first@email.com"},
{"sender": "John",
"email": "second@email.com"},
{"sender": "Jack",
"email": "third@email.com"}]
How would this be achievable in an easy to read and efficient manner? 如何以易于阅读和有效的方式实现这一目标?
You can try 你可以试试
>>> 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'}]
This will convert list to dict 这会将列表转换为dict
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)
Another way of solving it.. 另一种解决方法..
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.