Stella
Stella

Reputation: 1564

how to convert two-dimensional list to another list with dict as elements

how to convert list1 to list2?

list1 =[[1, 11], [2, 22], [3, 33], [4, 44]]
list2 = [[{1:2},{11:22}],[{3:4},{33:44}]]

key of list 2 is odd elements of list1, while value of list2 is even number of list1

I've tried like below, but get different list3.

def f(list1):

    newlist=[]
    for i in range(0, len(list1), 2):
        dict1={}
        for j,key in enumerate (list1[i]):
            dict1[key]=list1[i+1][j]
            newlist.append(dict1)  
    print newlist



f(list1)
[{1: 2, 11: 22}, {1: 2, 11: 22}, {33: 44, 3: 4}, {33: 44, 3: 4}]

Upvotes: 0

Views: 102

Answers (7)

Adem Öztaş
Adem Öztaş

Reputation: 21446

In [27]: list1 =[[1, 11], [2, 22], [3, 33], [4, 44]]
In [28]: l2 = [ zip(item, list1[k+1]) for k,item in enumerate(list1) if k +1 < len(list1) and k % 2 == 0 ]
In [29]: [[{ item[0][0]: item[1][0]}, [{item[0][1]: item[1][1] }]  ] for item in l2]
Out[29]: [[{1: 11}, [{2: 22}]], [{3: 33}, [{4: 44}]]]

Upvotes: 1

Stella
Stella

Reputation: 1564

newlist=[]

for i in range(0, len(list1), 2):
   dict1={} 
   for j,key in enumerate (list1[i]):
        dict1[key]=list1[i+1][j]
   newlist.append([dict1])
print newlist

update my coding, from newlist.append(dict1) under 2nd for to newnlist.append([dict1]) under 1st for

Upvotes: 0

RickardSjogren
RickardSjogren

Reputation: 4238

As list comprehension:

list1 = [[1, 11], [2, 22], [3, 33], [4, 44]]
list2 = [[{tup[0]: tup[1]} for tup in zip(*list1[i:i+2])] for i in range(0, len(list1), 2)]
# Prints as [[{1: 2}, {11: 22}], [{3: 4}, {33: 44}]]

Edit: This one's a bit cleaner (and more pythonic perhaps).

list2 = [[dict([tup]) for tup in zip(*sublist)] for sublist in zip(list1[0::2], list1[1::2])]

Edit2: The list comprehension is equivalent to this nested for-loop.

list1 =[[1, 11], [2, 22], [3, 33], [4, 44]]
list2 = list()

# Iterate over list1 two by two, first round: sublist = ([1,11], [2,22])
for sublist in zip(list1[0::2], list1[1::2]):

    inner_result = list()

    # Second loop equivalent to for tup in zip(sublist[0], sublist[1])
    for tup in zip(*sublist):  # First round, tup will be (1,2) then (11, 22)    

        # Make dictionary from tuple, for first tuple this is
        # equivalent to: dict([(1,2)]) == {1: 2}
        new_dict = dict([tup])  
        inner_result.append(new_dict)

    list2.append(inner_result)

Upvotes: 2

RomanHotsiy
RomanHotsiy

Reputation: 5148

Your code is almost correct. The issue is here:

dict1={}
for j,key in enumerate (list1[i]):
  dict1[key]=list1[i+1][j]
  newlist.append(dict1)

In loop you're using the same dict. So to achieve what you want just move dict1 definition into the loop (create a new dict on each iteration):

for j,key in enumerate (list1[i]):
  dict1={}
  dict1[key]=list1[i+1][j]
  newlist.append(dict1)

Upvotes: 1

Vivek Sable
Vivek Sable

Reputation: 10223

Create List--> List--> dictionaries from the given list, consider 0th item is Key from the list1 and 1st item is value.

  1. Iterate every item from the list1 by enumerator because we want index of every item from the list1.
  2. Process on only those items which index is even means 0, 2, 4, ..
  3. Create list of dictionary’s from the Current Item and Next Item of the list1
  4. Append list of dictionary’s into result list.
  5. Handle exception for Index Error.

Demo:

>>> list1 =[[1, 11], [2, 22], [3, 33], [4, 44]]
>>> for i, value in enumerate(list1):
...     if i%2==0:
...         try:
...             result.append([{value[0]:list1[i+1][0]}, {value[1]:list1[i+1][1]}])
...         except IndexError:
...             print "Index Over"
...             break
... 
>>> result
[[{1: 2}, {11: 22}], [{3: 4}, {33: 44}]]

Upvotes: 1

jmlorenzi
jmlorenzi

Reputation: 162

Is this what you are looking for?

def f(lista):
    lnew = []
    i=0
    while i < len(lista):
        dict1 = {lista[i][0]:lista[i+1][0]}
        dict2 = {lista[i][1]:lista[i+1][1]}
        lnew.append([dict1,dict2])
        i += 2
    return lnew

lold = [[1, 11], [2, 22], [3, 33], [4, 44]]
print(f(lold))

Upvotes: 1

Saksham Varma
Saksham Varma

Reputation: 2130

Is this what you're looking for:

list2 = []
ind = 0
while ind < len(list1):
    d1 = {list1[ind][0]: list1[ind+1][0]}
    d2 = {list1[ind][1]: list1[ind+1][1]}
    list2.append([d1, d2])
    ind += 2
print list2        # prints [[{1: 2}, {11: 22}], [{3: 4}, {33: 44}]]

Upvotes: 1

Related Questions