Home > front end >  Append dict to list of dicts with counter
Append dict to list of dicts with counter

Time:12-07

I have this code:

def create_list(order_list):
    items_list = []
    for order in order_list:
        for o in order['items']:
            items_list.append(
                {'orderId': order['orderId'], 'name': o['name']} # add count of o['name']
            )
    
    return items_list
    
    
orders = [{'orderId': '1', 'items': 
            [
                {'name': 'sample', 'other_params': '1'}, 
                {'name': 'sample2', 'other_params': '2'}, 
                {'name': 'sample3', 'other_params': '3'}, 
                {'name': 'sample'}
            ]
        }]

tryme = create_list(orders)

print(tryme)

And the output is:

[{'orderId': '1', 'name': 'sample'}, {'orderId': '1', 'name': 'sample2'}, {'orderId': '1', 'name': 'sample3'}, {'orderId': '1', 'name': 'sample'}]

But the {'orderId': '1', 'name': 'sample'} repeated. How do I make it so that it doesn't repeat and also be able to print the count of the occurrences of each dict.

For example instead of having two {'orderId': '1', 'name': 'sample'}, I can just have {'orderId': '1', 'name': 'sample', 'count': 2}.

Also, is there a way to remove the nested for-loop?

CodePudding user response:

You didn't mentioned anything about what happens to the other_params, so I just ignored them and converted your orders into the format you wanted.

def convert_list(input_list):
  # Initialize an empty output list
  output_list = []

  # Iterate over the input list
  for item in input_list:
    # Get the order ID
    order_id = item['orderId']

    # Iterate over the list of items
    for i in item['items']:
      # Check if the current item is already in the output list
      exists = False
      for j in output_list:
        if j['name'] == i['name']:
          # If it exists, increment the count and set the flag
          j['count']  = 1
          exists = True
      if not exists:
        # If the item doesn't exist, add it to the output list with a count of 1
        output_list.append({'orderId': order_id, 'name': i['name'], 'count': 1})

  # Return the output list
  return output_list
  • Related