-1

I have a python list , and I want to create a dictionary with word as a key and number as a value. what is the efficient way of doing this. Here is the my code:

['a',100,'b',200,'c',300,'d',400]

I want to convert it into dictionary like {'a':100,'b':200,'c':300,'d':400} please help me.

Hackaholic
  • 19,069
  • 5
  • 54
  • 72

4 Answers4

0

Apply your list for this convert function.

def Convert(lst):
    res_dct = {lst[i]: lst[i + 1] for i in range(0, len(lst), 2)}
    return res_dct
    

lst = ['a', 100, 'b', 200, 'c', 300]
print(Convert(lst))
Ashish Dawkhar
  • 131
  • 1
  • 9
0

You can just loop through the list, and add to dictionary as key element at index, and as value element at index + 1. I write sample code for you to understand easier, I didn't use any builtin methods for conversion, I don't is there any methods for what you want, but there is always solution. Code:


list1 = ['a',100,'b',200,'c',300,'d',400]

dict1 = { }

# this is for loup which is used for "conversion"
for i in range(0, len(list1), 2):
    dict1[list1[i]] = list1[i+1]
    
for i in dict1:
    print("Key : " + i + " Value : " + str(dict1[i]))
LakiMancic
  • 31
  • 1
0

Pythonic way:

>>> lst = ['a',100,'b',200,'c',300,'d',400]
>>> dict(zip(lst[::2], lst[1::2]))
{'d': 400, 'c': 300, 'a': 100, 'b': 200}
Hackaholic
  • 19,069
  • 5
  • 54
  • 72
0

That's just one efficient line

{ key: value for key, value in zip(x[::2], x[1::2]) } # x is the input list

Explanation:

  • x[::2] - takes all even index elements of the list: slice the list at zero through the end with step of 2 (['a', 'b', 'c', 'd'])
  • x[1::2] - takes all odd index elements of the list: slice the list at index 1 through the end with step of 2 ([100, 200, 300, 400])
  • zip(x[::2], x[1::2]) - extracts a tuple of elements from both the inputs ([('a',100), ('b', 200), ('c', 300), ('d', 400)])
  • { key: value for key, value in zip(...) } - iterates on the (key=even elements, value=odd elements) tuples and creates the dictionary
DDomen
  • 1,808
  • 1
  • 7
  • 17