python-3.x - How to convert list of list into dictionary object?
问题描述
I have a list of lists that looks like this:
[[['1',
'1@1`']],
[['2', '2@2.com']],
[['3', '3@3.com']],
[['4', '4@4.com']],
[['5', '5@5.com']],
[['6', '6@6']],
[['7', '7@7']],
[['8', '8@8']],
[['8.5', '8.5@8.5']],
[['9', '9@9']],
[['10', '10@10']],
[['11', '11@11']],
[['12', '12@12']],
[['13', '13@13.com']],
[['14', '14@14.com']],
[['15', '15@15.com']],
[['16', '16@16.com']],
[['17', '17@17.com']],
[['18@18.com', '18']],
[['19', '19@19.com']]]
is there anyway I can clean up the list by making it into a dictionary object like so:
[{id:1,email:1@1},{id:2,email:2@2.com}]
Ideally if there are any emails in the id
spot they flipped to the email
spot?
解决方案
You can use a list comprehension:
In [1]: mylist = [[['1',
...: '1@1`']],
...: [['2', '2@2.com']],
...: [['3', '3@3.com']],
...: [['4', '4@4.com']],
...: [['5', '5@5.com']],
...: [['6', '6@6']],
...: [['7', '7@7']],
...: [['8', '8@8']],
...: [['8.5', '8.5@8.5']],
...: [['9', '9@9']],
...: [['10', '10@10']],
...: [['11', '11@11']],
...: [['12', '12@12']],
...: [['13', '13@13.com']],
...: [['14', '14@14.com']],
...: [['15', '15@15.com']],
...: [['16', '16@16.com']],
...: [['17', '17@17.com']],
...: [['18@18.com', '18']],
...: [['19', '19@19.com']]]
In [2]: [{'id': i, 'email': e} for i, e in (pair[0] if '@' not in pair[0][0] else reversed(pair[0]) for pair in mylist)]
Out[2]:
[{'id': '1', 'email': '1@1`'},
{'id': '2', 'email': '2@2.com'},
{'id': '3', 'email': '3@3.com'},
{'id': '4', 'email': '4@4.com'},
{'id': '5', 'email': '5@5.com'},
{'id': '6', 'email': '6@6'},
{'id': '7', 'email': '7@7'},
{'id': '8', 'email': '8@8'},
{'id': '8.5', 'email': '8.5@8.5'},
{'id': '9', 'email': '9@9'},
{'id': '10', 'email': '10@10'},
{'id': '11', 'email': '11@11'},
{'id': '12', 'email': '12@12'},
{'id': '13', 'email': '13@13.com'},
{'id': '14', 'email': '14@14.com'},
{'id': '15', 'email': '15@15.com'},
{'id': '16', 'email': '16@16.com'},
{'id': '17', 'email': '17@17.com'},
{'id': '18', 'email': '18@18.com'},
{'id': '19', 'email': '19@19.com'}]
If you have arbitrary nesting, you can try this:
def flatten(lst):
for sub in lst:
if isinstance(sub, list):
yield from flatten(sub)
else:
yield sub
[{'id': i, 'email': e} for i, e in (pair if '@' not in pair[0] else reversed(pair) for pair in zip(*[flatten(mylist)]*2))]
推荐阅读
- java - 无法迁移 Android 项目。问题是 Card.IO
- shell - 当退出代码不为零时,Golang exec.Command 返回 nil 错误
- android - 谷歌 OCR 使用 ARcore 检测到的锚文本
- mysql - 如何使用 SELECT 查询从两个表中输出结果 - 查询逻辑以限制从一个表中输出数据
- mysql - 如何在 Kubernetes 上访问 MySQL 作为服务?
- apache-spark - Spark Streaming 由于与正在读取的 Kafka 主题不同的错误而失败
- python - 如何决定是否在 ubuntu 终端启动时使用 miniconda
- angular - [key:string]:highcharts.d.ts 中的 ChartOptions 和 Chart 类中缺少任何内容
- node.js - 如何从 fetch api 调用中返回数据?
- swift - 使用 Swift 在 Firebase 中检索多个数据