Reputation: 394
I have a dictionary that is populated with wifi probe requests that are collected by an antenna. The keys in the dictionary the unique MAC addresses in the probe requests. The construction is this:
dictionary = {KEY=[MACADDRESS] : FIELDS=0:[FIRSTSEEN] 1:[LASTSEEN] 2:[DECIBEL] 3:[COUNTER] 4:[SSID]}
The dictionary could then look like this:
dictionary = {'00:00:00:00:00:01': ['Aug 18, 2017 18:15:56.081727942 CEST', 'Aug 18, 2017 18:25:37.669160369 CEST', '-60', 18, 'SSID1'],
'00:00:00:00:00:02': ['Aug 18, 2017 18:19:22.764895209 CEST', 'Aug 18, 2017 18:33:50.052906956 CEST', '-46', 5, 'SSID2'],
'00:00:00:00:00:03': ['Aug 18, 2017 18:18:53.489779683 CEST', 'Aug 18, 2017 18:45:53.489779683 CEST', '-62', 1, 'SSID3']}
Now let's say there are 100 entries and I want to produce a list ordered by the [LASTSEEN] timestamp value (value 1 of the key). How would I go about and do that?
I found a "similar" question with an answer, where the use of sorted(dictionary) with a lambda function is used, but I can't wrap my mind around how to apply it here, also it doesn't take the timestamp into account. I thought maybe somehow the timestamp could be converted to UNIX time, which could make the sorting process easier.
UPDATE (In order to clarify further):
I want to rearrange the keys of the dictionary (if possible) and keep all their values. I want to be able to run a sort function in the dictionary and then select the 3 newest like:
#Here I would sort the dictionary
sort_function()
#then I would print eg. 3 entries
count_to_3 = 0
for keys, values in dictionary.items():
count_to_3 += 1
print keys,values
if count_to_3 == 3:
break
The output would then be (sorted by second timestamp). Sorry if it seems confusing with the double timestamps:
00:00:00:00:00:03 ['Aug 18, 2017 18:18:53.489779683 CEST','Aug 18, 2017 18:45:53.489779683 CEST', '-62', 1, 'SSID3']
00:00:00:00:00:02 ['Aug 18, 2017 18:19:22.764895209 CEST','Aug 18, 2017 18:33:50.052906956 CEST', '-46', 5, 'SSID2']
00:00:00:00:00:01 ['Aug 18, 2017 18:15:56.081727942 CEST','Aug 18, 2017 18:25:37.669160369 CEST', '-60', 18, 'SSID1']
Upvotes: 0
Views: 1129
Reputation: 5384
By nature a dictionary is not sorted, so you can instead create a list of tuples with your key and values.
lst = sorted(d.items(), key = lambda kvp: kvp[1][1])
[('00:00:00:00:00:01', ['Aug 18, 2017 18:15:56.081727942 CEST', 'Aug 18, 2017 18:25:37.669160369 CEST', '-60', 18, 'SSID1']), ...]
Now what you need to be aware of is that because your time stamp is a string it may not sort exactly how you want it to. In that case you would have to convert it. For example some function to_datetime
.
lst = sorted(d.items(), key = lambda kvp: to_datetime(kvp[1][1]))
Upvotes: 1