python, sorting a dict/json

James Dugger james.dugger at gmail.com
Fri Feb 22 18:44:12 MST 2019


>
> import json
> from datetime import datetime
>
> with open('testp.json') as f:
>     data = json.load(f)
>
> for i in data['pubs']:
>     pub_date = datetime.strptime(i['date'], '%Y%m%d')
>     i['date'] = pub_date
>
> pub_list = sorted(data['pubs'], key=lambda k: k['date'])
>
> print(pub_list)
>
> open parses the json file into a python dictionary.  Currently the format
of your json will produce a dictionary with one key 'pubs' and a value
formatted as a python list of nested dictionaries.

The for loop targets the list inside the main dictionary and first converts
the date to a python date object.

 Then simply use the sorted method with a lambda expression to sort the
order of dictionaries by the newly created date objects.

Yor initial date values are integers.  You will need to either store them
in the json object as strings or convert them so that datetime.strptime()
can parse them.

I'm sure there are other ways to do this but this was the fastest given the
json format.

On Fri, Feb 22, 2019 at 12:21 PM der.hans <PLUGd at lufthans.com> wrote:

> moin moin,
>
> I'm trying to sort some data that is currently in json being imported into
> a dict.
>
> It's essentially bibliography information, but without a unique ID.
>
> I mostly want to sort on publication date, but also want to group by
> publication. There could be multiple publications on the same date.
>
> Currently using a json format like:
>
> {
>   "pubs": [
>    {
>     "date": 20190222
>     "title": "a title"
>     "url": "https://some.domain/page.html"
>    },
>    {
>     "date": 20190221
>     "title": "another title"
>     "url": "https://some.other.domain/page.html"
>    }
>   ]
> }
>
> Format can change if that helps.
>
> I want to be able to display items in order. Mostly chronological, but
> also by other details.
>
> Any suggestions for how to sort them for display?
>
> A nice, but not required, feature would be sorting them for saving to disk
> as well.
>
> ciao,
>
> der.hans
> --
> #  https://www.LuftHans.com   https://www.PhxLinux.org
> # "You want weapons? We're in a library! Books! The best weapons in the
> # world! This room's the greatest arsenal we could have - arm yourselves!"
> # -- the Doctor: Doctor Who, Tooth and Claw, 2006
> ---------------------------------------------------
> PLUG-discuss mailing list - PLUG-discuss at lists.phxlinux.org
> To subscribe, unsubscribe, or to change your mail settings:
> https://lists.phxlinux.org/mailman/listinfo/plug-discuss



-- 
James

*Linkedin <http://www.linkedin.com/pub/james-h-dugger/15/64b/74a/>*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.phxlinux.org/pipermail/plug-discuss/attachments/20190222/8f618b80/attachment.html>


More information about the PLUG-discuss mailing list