Andrea
Andrea

Reputation: 658

Return sorted list from nested dictionaries

I'm trying to create an ordered list based on the value of a nested dictionary.

Here's my source data:

data = {
    'countries': {
        'BE': {
            u'impressions': 0,
            u'requests': 807
        },
        'BG': {
            u'impressions': 0,
            u'requests': 130
        },
        'JP': {
            u'impressions': 0,
            u'requests': 1923
        }
    },
    'totals': {}
}

and here's the result I would expect:

list = [{'JP': { u'impressions': 0, u'requests': 1923 }}, {'BE': { u'impressions': 0, u'requests': 807 }}]

and finally the code I've written to do the filtering:

list = sorted(data["countries"], key=itemgetter('requests'))[:2]

But I get always this kind of error:

TypeError: string indices must be integers

I think the problem is that I'm using the wrong syntax to get the requests key from the dict... I tried different ways, but I always get similar errors. What am I doing wrong?

Upvotes: 1

Views: 71

Answers (2)

liuzhijun
liuzhijun

Reputation: 4469

>>> l = data['countries']
>>> l2 = [{key:l[key]} for key in l.keys()]
>>> sorted(l2, key=lambda x:x[x.keys()[0]]['requests'],reverse=True)

[{'JP': {u'impressions': 0, u'requests': 1923}}, 
 {'BE': {u'impressions': 0, u'requests': 807}},
 {'BG': {u'impressions': 0, u'requests': 130}}
]

Upvotes: 0

Ry-
Ry-

Reputation: 225125

Iterating a dictionary gives you its keys. You could use items instead:

sorted(data["countries"].items(), key=lambda kv: kv[1]["requests"])

Upvotes: 2

Related Questions