Skip to content

Instantly share code, notes, and snippets.

@iepathos
Last active May 4, 2018 15:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iepathos/7954228 to your computer and use it in GitHub Desktop.
Save iepathos/7954228 to your computer and use it in GitHub Desktop.
Explicitly sorting a dictionary by a sub-dictionary subkey into an ordered list.
# Dictionaries are inherently orderless, but lists are ordered!
import collections
d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
'124': { 'key1': 6, 'key2': 56, 'key3': 6 },
'125': { 'key1': 7, 'key2': 44, 'key3': 9 } }
results_list = []
sort_by_dict = {}
# this is going to hold the original index
# and the order like this {original_dict_index: order}
# Make a sorting dictionary full of the original key index and
# value of subkey3
value_dict = {}
for key in d:
value = d[key]
for subkey in value:
subvalue = value[subkey]
if subkey == 'key3':
original_index = key
subkey3value = subvalue
sort_by_dict[original_index] = subkey3value
# This is handles duplicate values with a number of occurences count
number_of_occurences = collections.defaultdict(int)
for key in sort_by_dict:
value = sort_by_dict[key]
number_of_occurences[value] += 1
# This is a sorted list not a dict, hence the i below ;)
sorted_number_occurences = sorted(number_of_occurences, key=number_of_occurences.get, reverse=True)
i = 0
for key in sorted_number_occurences:
subkey3value = sorted_number_occurences[i]
i += 1
for original_key in d:
if original_key in sort_by_dict.keys() and sort_by_dict[original_key] == subkey3value:
# Just adding faux dict {original_key: d[original_key]} to a results list
results_list.append({original_key: d[original_key]})
print results_list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment