简体   繁体   English

如何在python中将数组转换为dict

[英]how to convert an array to a dict in python

Now, I wanna convert an array to a dict like this:现在,我想将数组转换为这样的字典:

dict = {'item0': arr[0], 'item1': arr[1], 'item2': arr[2]...}

How to solve this problem elegantly in python?如何在python中优雅地解决这个问题?

You could use enumerate and a dictionary comprehension:您可以使用enumerate和字典理解:

>>> arr = ["aa", "bb", "cc"]
>>> {'item{}'.format(i): x for i,x in enumerate(arr)}
{'item2': 'cc', 'item0': 'aa', 'item1': 'bb'}

Suppose we have a list of int s:假设我们有一个int列表:

We can use a dict comprehension我们可以使用字典理解

>>> l = [3, 2, 4, 5, 7, 9, 0, 9]
>>> d = {"item" + str(k): l[k] for k in range(len(l))}
>>> d
{'item5': 9, 'item4': 7, 'item7': 9, 'item6': 0, 'item1': 2, 'item0': 3, 'item3': 5, 'item2': 4}
simpleArray = [ 2, 54, 32 ]
simpleDict = dict()
for index,item in enumerate(simpleArray):
    simpleDict["item{0}".format(index)] = item

print(simpleDict)

Ok, first line Is the input, second line is an empty dictionary.好的,第一行是输入,第二行是空字典。 We will fill it on the fly.我们将即时填充它。

Now we need to iterate, but normal iteration as in C is considered non Pythonic.现在我们需要迭代,但在 C 中的正常迭代被认为是非 Pythonic 的。 Enumerate will give the index and the item we need from the array. Enumerate 将从数组中给出索引和我们需要的项目。 See this: Accessing the index in Python 'for' loops .请参阅: 访问 Python 'for' 循环中的索引

So in each iteration we will be getting an item from array and inserting in the dictionary with a key from the string in brackets.因此,在每次迭代中,我们将从数组中获取一个项目,并使用括号中字符串中的键插入字典。 I'm using format since use of % is discouraged.我正在使用格式,因为不鼓励使用 %。 See here: Python string formatting: % vs. .format .请参见此处: Python 字符串格式: % 与 .format

At last we will print.最后我们将打印。 Used print as function for more compatibility.使用打印作为功能以获得更多兼容性。

you could use a dictionary comprehension eg.你可以使用字典理解,例如。

>>> x = [1,2,3]
>>> {'item'+str(i):v for i, v in enumerate(x)}
>>> {'item2': 3, 'item0': 1, 'item1': 2}

Use dictionary comprehension: Python Dictionary Comprehension使用字典理解: Python Dictionary Comprehension

So it'll look something like:所以它看起来像:

d = {"item%s" % index: value for (index, value) in enumerate(arr)}

Note the use of enumerate to give the index of each value in the list.请注意使用enumerate给出列表中每个值的索引。

您还可以使用dict()来构建您的字典。

d = dict(('item{}'.format(i), arr[i]) for i in xrange(len(arr)))

Using map , this could be solved as:使用map ,这可以解决为:

a = [1, 2, 3]
d = list(map(lambda x: {f"item{x[0]}":x[1]}, enumerate(a)))

The result is:结果是:

[{'item0': 1}, {'item1': 2}, {'item2': 3}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM