我正在构造一个字典(稍后将其制成JSON字符串)。我这样构造它:

data = {}
for smallItem in bigList:
    data[smallItem] = smallItem

我该如何使for循环一行?

最佳答案

您可以使用dict comprehension:

data = {smallItem:smallItem for smallItem in bigList}

您也可以使用 dict generator expression:
data = dict((smallItem, smallItem) for smallItem in bigList)

但是对dict的理解会更快。

至于将其转换为JSON字符串,您可以使用 json.dumps

关于python - 单行for循环来建立字典?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27715692/

10-12 01:36