I have some data, let's assume it looks like this:
arr = [10, 90, 45]
And a dictionary, looking like this:
mydict = {}
I want to append the data from arr
to the dictionary and i would like to store it like this:
mydict = {{'one': 10}, {'one': 90}, {'one': 45}}
I tried a simple loop:
for x in arr:
mydict.update({'one': x})
But that doesn't work, since it will just overwrite the records.
Is there any way to do this in Python?
You could simply do:
arr = [10, 90, 45]
lst = []
for e in arr:
lst.append({'one': e})
print(lst)
Output
[{'one': 10}, {'one': 90}, {'one': 45}]
Or if you prefer alist comprehension :
lst = [{'one' : e} for e in arr]
you can use map
arr = [10, 90, 45]
arrName = ['one', 'two', 'tree']
dictionary = dict(map(lambda(x, y:{x: y}))
or zip
arr = [10, 90, 45]
arrName = ['one', 'two', 'tree']
dictionary = dict(zip(arrName, arr))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.