0

I have the following object:

{
  a: {size: 4},
  b: {size: 8},
  c: {size: 2},
  d: {size: 3},
  e: {size: 9},
  f: {size: 23}
}

I need to sort this based on size in Python 2. I can find a lot of resource on shallow sorting, but I am not sure how to access the size value. I struggled with sorted and a lamba function, but it isn't working out. How do I go about this?

I last attempted this:

domains = sorted(items, key=lambda item: item['size'])

However got the error:

TypeError: string indices must be integers, not str

Edit

I used @smarx's example to fix. As I needed to rebuild the full object and not just the keys, I ended up using:

for name in sorted(items, key=lambda k: items[k]['size'], reverse=True):
8
  • You say you "struggled" and it "isn't working". Provide your code. What did you try, what did you expect, what didn't work and how? Provide a full minimal reproducible example. Note: It might help if you spelled lambda correctly (assuming you made same typo in code). Commented May 24, 2017 at 4:09
  • Presumably you wish to sort based on size ... but you don't explicitly say that ... be more explicit as to your problem Commented May 24, 2017 at 4:12
  • Correct on both counts, ShadowRanger and donkopotamus Commented May 24, 2017 at 4:13
  • You were very close ... hint your lambda is being given a tuple of key and value ... Commented May 24, 2017 at 4:16
  • @donkopotamus: No it isn't; looks like they're passing the dict, not the dict's items. The error is what you'd see if you tried to index the key (str). Commented May 24, 2017 at 4:17

2 Answers 2

3

Something like this?

d = {
    "a": {"size": 4},
    "b": {"size": 8},
    "c": {"size": 2},
    "d": {"size": 3},
    "e": {"size": 9},
    "f": {"size": 23}
}

print(sorted(d, key=lambda k: d[k]["size"]))

# output:
# ['c', 'd', 'a', 'b', 'e', 'f']

I converted the "object" to Python syntax. (I assume what I have above is what you meant?)

sorted takes a keyword argument key, which is a function that returns the thing to sort by. So I sorted using a key function that looks up the size for each key.

I hope that makes sense.

UPDATE

A couple other things you might want to try, depending on what output you're trying to get:

print(sorted(d.items(), key=lambda item: item[1]["size"]))
print(sorted(d.values(), key=lambda value: value["size"]))

If none of these help, please tell us what output you actually want (keys, values, both, something else?).

Sign up to request clarification or add additional context in comments.

3 Comments

Side-note: Calling .keys() is superfluous on Py3, and actively wasteful on Py2 (where it has to make extra temporary lists). dicts are already iterables of their keys, so omit the extraneous call.
@ShadowRanger Thanks! Edited.
This was it, thanks so much. @ShadowRanger I'm at that entry point in Python where every question is very stupid because you simply don't even know enough jargon to ask the right question. At least I know my questions are stupid. Hope you'll forgive me :)
0

Perhaps use sorted on dict.items(), and set the sorting key to the item's value (index 1)'s size key.

dct = {
    "a": {"size": 4},
    "b": {"size": 8},
    "c": {"size": 2},
    "d": {"size": 3},
    "e": {"size": 9},
    "f": {"size": 23}
} 
print(sorted(dct.items(), key=lambda d: d[1]["size"]))

Depends on what kind of output you want, this one returns:

[('c', {'size': 2}), ('d', {'size': 3}), ('a', {'size': 4}), 
 ('b', {'size': 8}), ('e', {'size': 9}), ('f', {'size': 23})]

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.