从列表制作字典
我有以下列表。
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.