your lambda expression is not making any sense:
You're actually trying to access and return the second element of the list: ['attribute1'] which obviously has only one element!
what you should write is:
sorted(itemList, key=lambda x: x['attribute1'][1]
^
|
missing variable matching an element of the list
so that x is an item of your itemList.
edit:
As a follow up, I am still confused why ['attribute1'] has only one element? In my example, I have 'attribute1': (1,2), isn't that "2" the second element?
well, because where you're getting confused is that ['attribute1'] is not x['attribute1'], but it is still a valid python syntax, which is the unnamed list containing one element, the string 'attribute1'.
As you've defined x as a list of tuples, you want to extract a value out of the tuple using the [] operator. But because that operator exists for a list, when you access a value off ['attribute1'], it is syntactically correct. But because ['attribute1'] only has one element, it is semantically incorrect, and thus yells list index out of range at you!
I'm not sure where you're getting confused here. The lambda expression is no magic, it's is strictly equivalent to the following:
def get_second_of_attribute1(x):
return x['attribute1'][1]
sorted(itemList, key=get_second_of_attribute1)
here, x is the parameter that sorted() gives to the function defined as the key parameter for each item of its first parameter, itemList, to make a comparison so the list returns as sorted.
In summary, the lambda expression, and generally speaking the python compiler does not guess what you're trying to do, it needs explicit and clear instruction. If you tell him something wrong, it will either yell at you (if it's impossible), or actually do it!
Like, if you were looking for first element of tuple in your itemList, then you'd end up having no error, but sorted returning a non-sorted list, as the key function would always return the same thing: 'attribute1'.
HTH!