-1

Im new to python so I apologize in advance if this is a bit rudimentary, but given the list:

lst = ['user1', 25, 'user2', 10, 'user3', 54]

how would I create a dictionary that would be:

usr_dict = {'user1': 25, 'user2': 10, 'user3': 54]  
Sapien
  • 1
  • 1

2 Answers2

0

This has already been answered here.

But here is a method that is a little easier to understand:

usr_dict = {}
for i in range(0, len(lst), 2):
    usr_dict[lst[i]] = lst[i + 1]
jdaz
  • 5,964
  • 2
  • 22
  • 34
  • ah ok thank you for that. It was the range part I was having trouble with. Much appreciated jdaz – Sapien Jun 03 '20 at 23:44
0

I think the best approach is a dict comprehension:

usr_dict = {x[::2]:x[1::2] for x in lst}

Celius Stingher
  • 17,835
  • 6
  • 23
  • 53