I have a Dictionary here:
test_dict = {'gfg': ['One', 'six', 'three'],
'is': ['seven', 'eight', 'nine'],
'best': ['ten', 'six']}
I tried:
for i in range(len(test_dict)):
values = list(test_dict.values())
keys = list(test_dict)
value_sorted_list = values[i]
value_sorted_list = keys[i]
keys_sorted_list = random.shuffle(value_sorted_list)
test_dict.update({f"{keys_sorted_list}":value_sorted_list})
I want to sort the keys alphabetically while the value list by length Something like this:
test_dict = {'best': ['six', 'ten'],
'gfg': ['One', 'six', 'three'],
'is': ['nine', 'eight', 'seven]}
I also want another function similar to the one i mentioned above but if the elements are similar length, to sort them randomly.
As well as another function to sort value list randomly.
CodePudding user response:
Sorting keys alphabetically and values by length.
new_dict = {}
for key in sorted(test_dict.keys()):
sorted_values = sorted(test_dict[key], key=len)
new_dict[key] = sorted_values
print(new_dict)
CodePudding user response:
This can be achieved with a dictionary comprehension as follows:
test_dict = {'gfg': ['One', 'six', 'three'],
'is': ['seven', 'eight', 'nine'],
'best': ['ten', 'six']}
new_dict = {k:sorted(v, key=len) for k, v in sorted(test_dict.items())}
print(new_dict)
Output:
{'best': ['ten', 'six'], 'gfg': ['One', 'six', 'three'], 'is': ['nine', 'seven', 'eight']}
CodePudding user response:
dict
preserves insertion order since 3.7.
Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.
Therefore, you can simply construct a new dictionary according to the sorted key and ensure the corresponding value is sorted. From the output your posted, the value is sorted by length first then alphabetically.
result = {key: sorted(value, key=lambda x: (len(x), x)) for key, value in sorted(test_dict.items())} # Thanks to Masklinn
print(result)
# {'best': ['six', 'ten'], 'gfg': ['One', 'six', 'three'], 'is': ['nine', 'eight', 'seven']}
Reference:
dict-comprehension
- a way to construct a dictionary
sorted
- The key function here achieves sorting by length first then alphabetically. You can change it according to your sorting rules.