Сonvert list values to dictionary as key and value

Viewed 61

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:

rline = ['1604780184', '10', '1604780194', '0', '1604780319', '99', '1604780320', '0']
total = {}
print(f"My list: {rline}")

while rline:
    total[rline[0:2][0]] = rline[0:2][1]
    del rline[0:2]

print(f"Dictionary: {total}")

Please advise a better way. Thanks.

2 Answers

Most concise (and probably the best) way might be:

result = dict(zip(lst[::2], lst[1::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!

I do not like to change a list while iterating over it. I'd prefer do this way:

i = 0
while i < len(rline):
  total[rline[i]] = rline[i+1]
  i = i + 2

print(f"Dictionary: {total}")
Related