Suppose there is a list: ['1604780184', '10', '1604780194', '0', '1604780319', '99', '1604780320', '0']
You need to get a result like: {'1604780184': '10', '1604780194': '0', '1604780319': '99', '1604780320': '0'}
Now I have so:
JavaScript
x
10
10
1
rline = ['1604780184', '10', '1604780194', '0', '1604780319', '99', '1604780320', '0']
2
total = {}
3
print(f"My list: {rline}")
4
5
while rline:
6
total[rline[0:2][0]] = rline[0:2][1]
7
del rline[0:2]
8
9
print(f"Dictionary: {total}")
10
Please advise a better way. Thanks.
Advertisement
Answer
Most concise (and probably the best) way might be:
JavaScript
1
2
1
result = dict(zip(lst[::2], lst[1::2]))
2
What it actually does is make use of some pattern your list follows and some builtin functions! Since every even index is a value-to-be and odd index a key-to-be, its easier to just slice and separate them. Then you can use zip()
to form a collection of these separated values and then call dict()
constructor to pull a dictionary out of it!