Skip to content
Advertisement

python dictionary group by , order by and create a new key based on rank

How to apply group by location, order by time and create a new key based on rank in python dictionary

li_input_dict

JavaScript

output out is required a new key name as new_name in the dictionary which need to append a number based on data group by location and order by timestamp

JavaScript

Edited after Mark comment

I tried to sort by time and order by location by below line but unable to use rank in dictionary ,sorry I am not much expert in python ,can do it in sql.

JavaScript

I am not looking the solution in pandas

Advertisement

Answer

First make a list of dictionaries sorted by location and time. This will put the groups together and within the groups they will be sorted by time:

JavaScript

Now you have a list l_sort that looks like:

JavaScript

Now that everything is in the correct place you can use itertools.groupby from the standard library to make groups based on location, then for each dict in each group update the dictionary:

JavaScript

This will update the dicts in place, so your original list will now have dicts like:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement