热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

从列表制作字典

我有以下列表。keys=[key1,key2,key3]value1=[1,2]value2=[10,20]v

我有以下列表。

keys = ["key1", "key2", "key3"]
value1 = [1,2]
value2 = [10,20]
value3 = [100,200]

我怎样才能得到像[{"key1":1, "key2":10, "key3":100},{"key1":2, "key2":20, "key3":200}]使用 python一样的结果?

我尝试了 for 循环,但找不到任何解决方案。

提前致谢

回答

您可以使用列表理解来首先zip元素化您的值,然后通过根据您的键压缩这些值来创建字典。

>>> [dict(zip(keys, i)) for i in zip(value1, value2, value3)]
[{'key1': 1, 'key2': 10, 'key3': 100}, {'key1': 2, 'key2': 20, 'key3': 200}]



  • Sure, it gets the job done for the OP for the example posted, but IMHO it's too terse an answer for someone ostensibly having trouble with for loops.


  • @navneethc So I should avoid providing a pythonic answer even though it is concise and correct? If the OP has any questions about this solution they are free to ask follow-up questions. No reason to make assumptions about what other people know, or want to learn about. If they are unfamiliar with list comprehensions, now is great time to learn about them.


  • That said, what was unreasonable to assume was that I somehow said that you should avoid providing a pythonic answer.





推荐阅读
author-avatar
再见傻瓜傻瓜_299
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有