Reputation: 613
I am creating a dictionary with values as a list of integers. What is the pythonic way to sort the values for each key? In my approach I am overwriting each key value after sorting.
Is there a way to maintain the sorting on insertion into the dictionary or is it better to store first and then sort the values efficiency wise?
my_dict = {
'first': [3,6,99],
'second': [1,-10,100],
'third': [5,0,23,67,29]
}
# my approach
for key, values in my_dict.items():
my_dict[key] = sorted(values)
Ouput:
my_dict = {
'first': [3,6,99],
'second': [-10,1,100],
'third': [0,5,23,29,67]
}
Upvotes: 2
Views: 273
Reputation: 1258
pythonic code makes use of programming patterns such as list comprehensions or generator expressions, attempt to crowbar in patterns more commonly used in C or java. Loops are particularly common examples of this.Pythonic code also makes use of inline sintaxes as mentioned by PEP20(Beautiful is better than ugly.
, Flat is better than nested.
)
Firstly, your code is good but to be more pythonic you should make use of sytaxes such as list comprehnsions/dict comprehensions. I will cover the most efficient way that has the least lines of code using a dict comprehension instaed of a for loop to be more pythonic even hough for loops are considered to be pyhonic list & dict comprehensions are more pythonic(they are flat syntaxes).
Here is the code:
my_dict = {
'first': [3,6,99],
'second': [1,-10,100],
'third': [5,0,23,67,29]
}
sorted_dict = {key:sorted(value) for key, value in my_dict.items()}
print(sorted_dict)
Output:
{'first': [3, 6, 99], 'second': [-10, 1, 100], 'third': [0, 5, 23, 29, 67]}
Upvotes: 0
Reputation: 42746
You were almost there, you want to sort the lists in place, so use list.sort
:
my_dict = {
'first': [3,6,99],
'second': [1,-10,100],
'third': [5,0,23,67,29]
}
for val in my_dict.values():
val.sort()
Check this sorting how to guide
Upvotes: 2