1

How to create a dictionary from List when my list is like below

L1 = [1,2,3,4,5,6,7,8,9]

and I want the result as a dictionary like

d = {'1':[2,3], '4':[5,6], '7':[8,9]}

Is any idea, how to implement this?

  • No predefined way to do this, write a loop which increments by 3 and inside that loop add first as key and next 2 elements as value list. – anuragal Sep 20 '17 at 08:45

2 Answers2

0
L = [1,2,3,4,5,6,7,8,9]
n = 3
dict = {}

for i in range(0, len(L), n):
#this creates chunks of size n
    sub_list = L[i:i+n]
    dict[sub_list[0]] = sub_list[1:]

print(dict)

To get dictionary entries of size 2, choose n=3 in this example.

LcdDrm
  • 1,009
  • 7
  • 14
0

one-liner:

dict((L1[i*3], [L1[i*3+1], L1[i*3+2]]) for i in xrange(len(L1)/3))

Explanation:

xrange(len(L1)/3) returns a lazy range from 0 to 2: [0, 1, 2]. Further for each element i of a range it transforms to a tuple (k, [v1, v2]]). So the final range will be [(1, [2, 3]), (4, [5, 6]), (7, [8, 9])]. And finally we use a dict constructor from list of tuples where each element considered as a key-value pair.

Final result is {1: [2, 3], 4: [5, 6], 7: [8, 9]}. To convert keys from number to string we need to replace L1[i*3] to str(L1[i*3]).

Zefick
  • 2,014
  • 15
  • 19