-3
To sort a list of tuples by value. For example:
x=[{"nome":1},{"data":4},{"dia":5}]
I’d like you to stay:
x=[{"dia":5},{"data":4},{"nome":1}]
-3
To sort a list of tuples by value. For example:
x=[{"nome":1},{"data":4},{"dia":5}]
I’d like you to stay:
x=[{"dia":5},{"data":4},{"nome":1}]
0
Welcome to Stack Overflow! First of all, what you have is not a list of tuples, but a list of dictionaries. A list of tuples would be this:
lista = [('dia',5),('data',4),('nome',1)]
Now that we understand this, the easiest way to organize this list is by using the method sort
passing to the parameter key
a function that has a parameter called "key" where each item in the list will be passed and that function must return a value.
The return value will be compared with the other values obtained and the list will be organized based on these values in descending order. That is why until the parameter name is called "key", because the return of the function will not be a value to be inserted in the list, but the "key" of the list. Example:
def organiza(key):
if key%2 == 0: key += 2
return key
lista = [1,2,3,4]
lista.sort(key=organiza)
print(lista)
The exit will be: [1, 3, 2, 4]
This happened because there in the function organiza
, I told Python to add +2
for whatever value it was par. Soon the key to 3 would be 3 and the key to 2 would be 4. Since the number three is less than four, the value 3
stands in front of the 2
on the list.
Browser other questions tagged python python-3.x
You are not signed in. Login or sign up in order to post.
Note: you have a list of dictionaries, not tuples.
– Woss
hi Raiza, please enter the code of the attempts you have made and instead of asking how to ask ask what you are doing wrong after trying, take a look also at the [tour] platform :)
– RFL