1

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?

2 Answers 2

2

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

sorted(data["countries"].items(), key=lambda kv: kv[1]["requests"])
1
  • Oh, yep. Looks like you want reverse=True, too.
    – Ry-
    Oct 28, 2013 at 1:28
0
>>> 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}}
]
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.