2

I have an array that contains several type of dict, as example:

arr = [
    {'type': 'employee.update', ...}, 
    {'type': 'job.started', ...}, 
    {'type': 'meeting.xpto', ...}
    ...
]

How can I split the "main" array by prefix of type? Is necessary to iterate over entire array for every prefix?

employess_actions = list(filter(lambda x: x['type'].startswith('employee.'), arr))
job_actions = list(filter(lambda x: x['type'].startswith('job.'), arr))
meeting_actions = list(filter(lambda x: x['type'].startswith('meeting.'), arr))

Is there any performatic way of achieve it? Or a pythonic way.

1
  • Wouldn't it simpler to just loop over arr ? Commented Jul 5, 2020 at 14:39

2 Answers 2

2

You could use a (default)dict for collecting the elements by prefix:

from collections import defaultdict
result = defaultdict(list)
for o in arr:
    result[o["type"][:o["type"].index(".")]].append(o)

This assumes of course that all those types have a "." in them.

For example, if:

arr = [
    {"type": "employee.update"}, 
    {"type": "job.started"}, 
    {"type": "meeting.xpto"},
    {"type": "job.ended"}
]

then the resulting result is

{
  "employee": [{"type": "employee.update"}],
  "job":      [{"type": "job.started"}, {"type": "job.ended"}],
  "meeting":  [{"type": "meeting.xpto"}]
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could iterate over arr, group each type with a collections.defaultdict using the the prefix as the key. We can use str.split() to split the type on ., then unpack the prefix using tuple unpacking.

from collections import defaultdict

arr = [
    {'type': 'employee.update'}, 
    {'type': 'job.started'}, 
    {'type': 'meeting.xpto'}
]

types = defaultdict(list)
for dic in arr:
    prefix, _ = dic["type"].split(".")
    types[prefix].append(dic)

print(types)

Output:

defaultdict(<class 'list'>, {'employee': [{'type': 'employee.update'}], 'job': [{'type': 'job.started'}], 'meeting': [{'type': 'meeting.xpto'}]})

If we want to only append the type and not the full dictionary:

types[prefix].append(dic["type"])

Which will give instead:

defaultdict(<class 'list'>, {'employee': ['employee.update'], 'job': ['job.started'], 'meeting': ['meeting.xpto']})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.