I need to sort dictionnary by specific function, i used a function returned by an AI that seems logic but i have an error on the x parameter from: “reverse=True if x[1] >= 0 else False”
error = “NameError: name ‘x’ is not defined”
Do you have an idea why x is not recognized from the lambda?
Here an example of what i need:
dict = {"value1" : "1", "value2" : "2", "value3" : "-2", "value4" : "-5", "value5" : "0"}
dict_sorted = {"value2" : "2", "value1" : "1", "value5" : "0", "value3" : "-2", "value4" : "-5"}
And here the function i tried:
def sort_dictionary(dico):
"""Sorts the values in a dictionary according to the criterion: positive decreasing, negative increasing.
Args:
dico: The dictionary to sort.
Returns:
A new dictionary sorted.
"""
# Extract key-value pairs
items = dico.items()
# Sort pairs based on value
items_tries = sorted(items, key=lambda x: x[1], reverse=True if x[1] >= 0 else False)
# Create a new sorted dictionary
dico_trie = dict(items_tries)
return dico_sort
Vega is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
The values in your source dictionary are strings but it looks like you want to treat them as numbers (integers). Also, the key “value2” occurs twice so the value of “2” will be overridden by “-5”. You can’t have duplicate keys in a dict.
Therefore,
d = {"value1" : "1", "value2" : "2", "value3" : "-2", "value2" : "-5", "value5" : "0"}
ds = dict(sorted(d.items(), key=lambda x: int(x[1]), reverse=True))
print(ds)
Output:
{'value1': '1', 'value5': '0', 'value3': '-2', 'value2': '-5'}
Optionally (using a dictionary comprehension):
ds = {k: v for k, v in sorted(d.items(), key=lambda x: int(x[1]), reverse=True)}
2