Python 单行 for 循环来构建字典?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27715692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Single line for-loop to build a dictionary?
提问by easythrees
I'm constructing a dictionary (which I'll later make into a JSON string). I construct it like this:
我正在构建一个字典(稍后我将把它变成一个 JSON 字符串)。我这样构造它:
data = {}
for smallItem in bigList:
data[smallItem] = smallItem
How can I make that for loop one line?
我怎样才能让它循环一行?
采纳答案by easythrees
You can use a dict comprehension:
您可以使用字典理解:
data = {smallItem:smallItem for smallItem in bigList}
You might also use dict
and a generator expression:
data = dict((smallItem, smallItem) for smallItem in bigList)
But the dict comprehension will be faster.
但是字典理解会更快。
As for converting this into a JSON string, you can use json.dumps
.
至于将其转换为 JSON 字符串,您可以使用json.dumps
.
回答by jamylak
Actually in this specific case you don't even need a dictionary comprehension since you are using duplicate key/value pairs
实际上,在这种特定情况下,您甚至不需要字典理解,因为您使用的是重复的键/值对
>>> bigList = [1, 2, 3, 4, 5]
>>> dict(zip(bigList, bigList))
{1: 1, 2: 2, 3: 3, 4: 4, 5: 5}