Home > Software design >  How to reorder elements in nested lists?
How to reorder elements in nested lists?

Time:11-03

How to reorder elements in nested lists? (python 3)

I want to get values from y and put them in order of elements in x. Afterward, I need to put my result in another list in exact order. How can I reorder elements to get the expected result? This is what I've done so far:

def make_lists(x,y):
  b=[]
  order=[]
  for i in range(len(x)):
    order.append(i)
  for dic in y:
    a=[]
    for key in dic.keys():
      for stuff in x:
        if stuff==key:
          a.append(dic[key])
    b.append(a)
  return b

print(make_lists(['Hint', 'Num'],
         [{'Hint': 'Length 2 Not Required', 'Num' : 8675309},
          {'Num': 1, 'Hint' : 'Use 1st param order'}]))

Output

[['Length 2 Not Required', 8675309], [1, 'Use 1st param order']

Expected

[['Length 2 Not Required', 8675309], ['Use 1st param order', 1]

CodePudding user response:

The previous answer is elegant. But, if you want to do this is in a basic manner, here is the code. One considerable advantage is that we do not assume that the key exists in "order" list. If the element is not present, the "None" is appended in its place.

order = ['Hint', 'Num']
dictionaries = [{'Hint': 'Length 2 Not Required', 'Num' : 8675309},
                {'Num': 1, 'Hint' : 'Use 1st param order'}]

def make_lists(x, y):     
    all_lists = [] # This is the final list that will be returned
    # First, we loop through each dictionary 
    for dic in y: 
        list_ = []
        # In each dictionary, we get the values in 
        # the right order and then append it to a list
        for key in x:
            required_value = dic.get(key)
            list_.append(required_value)
        # We finally append our list - which is in right order 
        # to another list that will be returned
        all_lists.append(list_)
    return all_lists


print(make_lists(order, dictionaries))

The logic is to loop through the dictionaries. For each dictionary, you append the values in the correct order.

Output:

[['Length 2 Not Required', 8675309], ['Use 1st param order', 1]]
[["Hint", "Num"], ["Hint", "Num"]]

CodePudding user response:

One way using operator.itemgetter:

Note: This assumes the keys are always present in the target dicts.

from operator import itemgetter

list(map(itemgetter("Hint", "Num"), dicts))

Or just list comprehension with dict.get, so that it can handle missing keys:

[[d.get(k) for k in keys] for d in dicts]

Output:

[('Length 2 Not Required', 8675309), ('Use 1st param order', 1)]
  • Related